How to apply a value to a list of functions

I would like to achieve:

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

this is a kind of inverse mapping:

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

I tried Hoogle, but to no avail. Can anyone suggest a clean way to do this in Haskell?

+6
source share
2 answers
 apply :: a -> [a -> b] -> [b] apply a = map ($ a) 

which is a meaningful way to say

 apply a = map (\f -> fa) 

which could be more understandable.

+15
source

\a -> map ($ a) definitely fine, but maybe even better - Applicative : yes

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

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

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

Although in reality I would prefer to restrict the signature a -> [a->b] -> [b] for this top-level binding, since Applicative pretends that you have the most common signature, which it is not:

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

Indeed, my solution is probably best when you are in some kind of pipeline, I believe that it is better not to define apply , but to use (<**>) . pure (<**>) . pure directly in the code.

+3
source

Source: https://habr.com/ru/post/950307/


All Articles