How to apply a traversable of functions to a one value

放肆的年华 提交于 2021-01-28 17:49:28

问题


What should I use if I want to have something like

[a->b] -> a -> [b]

basically I have a list of functions, all take in a value a and returns b. I want to apply all of them to one a and get the results [b].

Which one should I use?

Thanks


回答1:


You don't need Traversable, just Functor:

swingMap f x = fmap ($ x) f

See also the swing function (this is equivalent to swing fmap).


Or, if you're using Edward Kmett's distributive library, you can have the best of both this answer (only a Functor rather than a Traversable) and chi's answer (avoiding defining a custom function for the job), by using distribute from Data.Distributive.




回答2:


You could use sequence, specialized to the (->) a monad. In this way you can avoid defining a custom function for the job -- it's already there.

> :t sequence
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)
> :t sequence :: [a->b] -> a -> [b]
sequence :: [a->b] -> a -> [b] :: [a -> b] -> a -> [b]
> sequence [id,(10+),(10-)] 3
[3,13,7]

(sequenceA and traverse id, being the same, would also work)




回答3:


When functions appear in a data type it's time to remember applicatives because that's what it is. One might easily do this job like;

appList :: [a->b] -> a -> [b]
appList fs x = fs <*> pure x

λ> appList [(+1), (*2), subtract 3] 5
[6,10,2]


来源:https://stackoverflow.com/questions/60609740/how-to-apply-a-traversable-of-functions-to-a-one-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!