0

I'm a data analyst, not a software developer, and I often find myself writing a function like this (shown in Python syntax here):

def apply_many(arg, *funcs):
    return [func(arg) for func in funcs]

so I can do things like

from random import random

# generate 10 random numbers for demonstration
x = [random() for _ in range(10)]

def mean(x):
    return sum(x) / len(x)

result = apply_many(x, min, mean, max)

Which returns the minimum, mean, and maximum in x:

[0.022936866501094166, 0.3962645320243164, 0.7520986774090447]

That little apply_many function (with a few additional tweaks) routinely saves a lot of typing for me, and I also believe it makes for more readable code.

Is there some kind of accepted name for this thing? Is there a use for it in proper functional programming?

1
2

I don't know if there's an accepted named for it, but it is really just a form of map:

apply: ('a -> 'b) list -> 'a -> 'b list
apply functions arg = map (\f -> f arg) functions

That's not particularly interesting, but there you have it.

4
  • Indeed, and that's how I usually have it implemented in R (lapply) and Python (either map or a list comprehension as shown in the question). I suppose there isn't a name for it because it's not a very useful idiom in production code situations? – shadowtalker Oct 12 '16 at 0:17
  • 4
    It's a very useful idiom. Why do you insist on a fancier name than apply or map? – Robert Harvey Oct 12 '16 at 0:23
  • Production code situations is not really relevant. Functions that are given common, widespread names are usually theoretically interesting: map, fold, accum, bind, etc. Honestly, I just don't think this code is interesting enough to warrant it's own name. – gardenhead Oct 12 '16 at 0:23
  • If you're interested, I've since realized that the term I was looking for is "juxtaposition". This of course is not really the same as what I described in the question, but I'm pretty sure it's what I had in mind at the time. – shadowtalker Feb 16 at 15:54
1

Since asking this question, I have seen a similar pattern referred to as "juxtaposition" or "juxt" (see e.g. https://clojuredocs.org/clojure.core/juxt).

A simple Python implementation would be:

def juxt(*funcs):
    def _f(x):
        return [f(x) for f in funcs]
    return _f

from random import random

data = [random() for _ in range(10)]

juxt(min, mean, max)(data)

This of course is not the same pattern, but I'm pretty sure this is what I had in mind when I originally asked the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.