将函数列表应用于值的简单方法 [英] Simple way to apply a list of functions to a value
本文介绍了将函数列表应用于值的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个函数列表 List [A => B]
并且需要一个返回 List [B]
的函数,用于类型为 A $ c $的给定值c>:
Suppose I've got a list of functions List[A => B]
and need a function that returns List[B]
for a given value of type A
:
def foo[A, B](fs: List[A => B]): A => List[B] = a => fs.map(_.apply(a))
有没有更简单的(可能用 cats
)写入列表[A => B] => A =>列表[B]
?
Is there any simpler (maybe with cats
) way to write List[A => B] => A => List[B]
?
推荐答案
正如@Oleg指出的那样,您可以使用应用
来生成函数:
As @Oleg points out, you can use Applicative
to generate the function:
import cats.implicits._
def foo[A, B](fs: List[A => B]): A => List[B] = a => fs ap List(a)
尽管我不认为它在这个特定方面有很大的不同情况。
Although I don't think it makes much of a difference in this particular case.
这篇关于将函数列表应用于值的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文