Scala将函数列表应用于对象 [英] Scala apply list of functions to a object
本文介绍了Scala将函数列表应用于对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多功能
val f1 = (x: Int) => x + 1
val f2 = (x: Int) => x + 2
val f3 = (x: Int) => x + 3
我只有一个值:
val data = 5
我想将所有函数应用于该值并返回单个值.所以
I want to apply all the functions to the value and return single value. So
f3(f2(f1(data)))
并且必须返回 11.
现在,如果我有一系列函数:
Now, if I have a seq of functions:
val funcs = Seq(f1, f2, f3)
如何通过将所有函数应用于 data
变量来获得 11
?这样做的Scala方式是什么?
How can I get 11
from applying all the functions to the data
variable ? What is the scala-way to do that ?
推荐答案
您正在寻找的是 foldLeft
.实际上,对于每个函数,您都将其应用到之前的结果中:
What you are looking for is foldLeft
. Indeed, for each function, you apply it to the previous result:
funcs.foldLeft(data){ (previousres, f) => f(previousres) }
这篇关于Scala将函数列表应用于对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文