I have a lit of functions
val f1 = (x: Int) => x + 1
val f2 = (x: Int) => x + 2
val f3 = (x: Int) => x + 3
I have a single value:
val data = 5
I want to apply all the functions to the value and return single value. So
f3(f2(f1(data)))
And must return 11.
Now, if I have a seq of functions:
val funcs = Seq(f1, f2, f3)
How can I get 11
from applying all the functions to the data
variable ? What is the scala-way to do that ?
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) }
yet another way to doing it using chain
method in the Function
helper object
Function.chain(funcs)(data)
you can use foldLeft
:
val result = funcs.foldLeft(5)((acc,curr) => curr(acc) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With