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?
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.
\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With