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?
-
3It's simply an Apply function. See en.wikipedia.org/wiki/ApplyRobert Harvey– Robert Harvey10/11/2016 23:27:06Commented Oct 11, 2016 at 23:27
2 Answers 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.
-
Indeed, and that's how I usually have it implemented in R (
lapply
) and Python (eithermap
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– shadowtalker10/12/2016 00:17:16Commented Oct 12, 2016 at 0:17 -
4It's a very useful idiom. Why do you insist on a fancier name than
apply
ormap
?Robert Harvey– Robert Harvey10/12/2016 00:23:28Commented Oct 12, 2016 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– gardenhead10/12/2016 00:23:53Commented Oct 12, 2016 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– shadowtalker02/16/2021 15:54:18Commented Feb 16, 2021 at 15:54
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.