user3663882 user3663882 - 3 months ago 19
Scala Question

Combining partial functions

I came from Java and would like to combine two partial functions like this:

def sum(a: Int, b: Int, c: Int) : Int = a + b + c


I want write something like this:

val l = List(1, 2, 3)
l.foreach(println _ sum (1, _ : Int, 3) ) // It's supposed to apply
// the partial sum(1, _: Int, 3)
// and println computed value.


But it refuses to compile. Is there a way to fix it concisely?

Answer

Assuming I reading what you want correctly (and even the code it's a huge assumption), here a snippet that might achieve it:

scala> def sum(a: Int, b: Int, c: Int) : Int = a + b + c
sum: (a: Int, b: Int, c: Int)Int

scala> val sum13 = sum(1, _ : Int, 3)
sum13: Int => Int = <function1>

scala> val printInt = println( _ : Int )
printInt: Int => Unit = <function1>

scala> List(1,2,4) foreach { printInt compose sum13 }
5
6
8

Notice the compose. Another way would be explicitly compose x => printInt(sum13(x)).

Comments