本文介绍了如何将一个可遍历的函数应用于一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想要

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

基本上我有一个函数列表,所有函数都取一个值 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].

我应该使用哪个?

谢谢

推荐答案

您不需要 Traversable ,只需 Functor :

swingMap f x = fmap ($ x) f

另请参见 Swing 函数(这等效于 swing fmap ).

或者,如果您使用的是 Edward Kmett distributive ,您可以同时兼顾这两个答案(只有一个 Functor而不是 Traversable )和 chi的答案(避免为作业),方法是使用 从Data.Distributive 中分发.

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.

这篇关于如何将一个可遍历的函数应用于一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:44
查看更多