Haskell apply single value to a list of functions

Basically this is an applicative job. You may do like

λ> [(+3), (*4), (+1)] <*> pure 3 -- or [3]
[6,12,4]

You also can use list comprehension for this. This line is enough for your example:

[ f 3 | f <- [(+3), (*4), (+1)] ]

This applies every function in the list on the right hand side to the value (3 in this case) on the left hand side.


For a more general version, this could be helpful:

applyFuns :: [(a->b)] -> a -> [b]
applyFuns fs x = [ f x | f <- fs ]

applyFuns [(+3), (*4), (+1)] 3

The Function applyFuns takes a list of functions from Type a->b as the first and a value of type b as the second. The result is a list of type b that contains the result of every function in the first list applied to the second argument.


You can use the $ operator, which stands for function application.

> map ($ 3) [(+3), (*4), (+1)]
[6,12,4]

This basically expands to [(+3) $ 3, (*4) $ 3, (+1) $ 3], which is just function application.


If flist is the list of functions and x is the argument, you need map (\f -> f x) flist.

For example

Prelude> map (\f -> f 10) [(4 +), (3 *)]
[14,30]

Tags:

Haskell