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

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 (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
  • 2
    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

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.