Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala apply list of functions to a object

Tags:

scala

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 ?

like image 957
artyomboyko Avatar asked Feb 04 '17 10:02

artyomboyko


Video Answer


3 Answers

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) }
like image 68
Omar Avatar answered Oct 10 '22 22:10

Omar


yet another way to doing it using chain method in the Function helper object

Function.chain(funcs)(data)
like image 35
rogue-one Avatar answered Oct 10 '22 23:10

rogue-one


you can use foldLeft:

val result = funcs.foldLeft(5)((acc,curr) => curr(acc) )
like image 36
Raphael Roth Avatar answered Oct 10 '22 23:10

Raphael Roth