Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a sequence of functions to value and get the final result

Tags:

scala

I wish to apply a sequence of functions to an object (each of the functions may return the same or modified object) and get the ultimate result returned by the last function.

Is there an idiomatic Scala way to turn this (pseudocode):

val pipeline = ListMap(("a" -> obj1), ("b" -> obj2), ("c" -> obj3))

into this?

val initial_value = Something("foo", "bar")
val result = obj3.func(obj2.func(obj1.func(initial_value)))

The pipeline is initialized at runtime and contains an undetermined number of "manglers".

I tried with foreach but it requires an intermediate var to store the result, and foldLeft only works on types of ListMap, while the initial value and the result are of type Something.

Thanks

like image 776
madprogrammer Avatar asked Feb 08 '23 22:02

madprogrammer


1 Answers

This should do it:

 pipeline.foldLeft(initial_value){case (acc, (k,obj)) => obj.func(acc)}

No idea why pipeline contains pairs, though.

like image 91
The Archetypal Paul Avatar answered Feb 28 '23 08:02

The Archetypal Paul