Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a value to a list of functions

What I'd like to achieve is:

apply :: a -> [a -> b] -> [b]

this is kind of the inverse of map:

map :: (a -> b) -> [a] -> [b]

I've tried Hoogle, but to no avail. Can anyone suggest a clean way of doing this in Haskell?

like image 594
OllieB Avatar asked Jul 25 '13 21:07

OllieB


Video Answer


2 Answers

apply :: a -> [a -> b] -> [b]
apply a = map ($ a)

which is a pithy way of saying

apply a = map (\f -> f a)

which may be more clear.

like image 180
J. Abrahamson Avatar answered Nov 01 '22 17:11

J. Abrahamson


\a -> map ($ a) is definitely fine, but perhaps yet a bit nicer is an Applicative approach: there is

<**> :: Applicative f => f a -> f (a -> b) -> f b

which has an instance <*> :: [a] -> [a->b] -> [b]. Looks a lot like what you want! You just need to put your a value in a singleton list, for which there is also a dedicated function in Applicative: pure.

apply :: Applicative f => a -> f (a -> b) -> f b
apply = (<**>) . pure

Though actually, I would rather restrict the signature to a -> [a->b] -> [b] for this top-level binding, since Applicative makes it look like you have the most general signature possible, which it is not:

apply :: Functor f => a -> f (a -> b) -> f b
apply a = fmap ($ a)

Really, my solution is probably best when you're in some pipeline, I daresay it's best not to define apply but use (<**>) . pure directly in the code.

like image 26
leftaroundabout Avatar answered Nov 01 '22 17:11

leftaroundabout