artyomboyko
artyomboyko

Reputation: 2871

Scala apply list of functions to a object

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 ?

Upvotes: 8

Views: 3875

Answers (4)

oblivion
oblivion

Reputation: 6568

Basically, you are trying to achieve Function Composition here. So, you could use compose and andThen methods here as:

    val data = 5

    val funcs = Seq(f1, f2, f3)

    //using compose
    val result1 = funcs.reduce((a,b) => a.compose(b))(data)

    //using andThen
    val result2 = funcs.reduce((a,b) => a.andThen(b))(data)

Both result1 and result2 will be 11 in your example.

Please note that the way andThen and compose operate are different. You could see Functional Composition for more information.

Upvotes: 2

rogue-one
rogue-one

Reputation: 11587

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

Function.chain(funcs)(data)

Upvotes: 12

Raphael Roth
Raphael Roth

Reputation: 27383

you can use foldLeft:

val result = funcs.foldLeft(5)((acc,curr) => curr(acc) )

Upvotes: 2

Omar
Omar

Reputation: 973

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) }

Upvotes: 12

Related Questions