Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get (a, b) => c from a => b => c in Scala?

If I have:

val f : A => B => C

This is shorthand for:

val f : Function1[A, Function1[B, C]]

How do I get a function g with the signature:

val g : (A, B) => C = error("todo")

(i.e.)

val g : Function2[A, B, C] //or possibly
val g : Function1[(A, B), C]

in terms of f?

like image 619
oxbow_lakes Avatar asked Aug 11 '10 09:08

oxbow_lakes


People also ask

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .


2 Answers

scala> val f : Int => Int => Int = a => b => a + b
f: (Int) => (Int) => Int = <function1>

scala> Function.uncurried(f)
res0: (Int, Int) => Int = <function2>
like image 57
retronym Avatar answered Sep 26 '22 01:09

retronym


Extending retonym's answer, for completeness

val f : Int => Int => Int = a => b => a + b
val g: (Int, Int) => Int = Function.uncurried(f)
val h: ((Int, Int)) => Int = Function.tupled(g)

The converse functions for both of these operations are also provided on the Function object, so you could write the above backwards, if you wished

val h: ((Int, Int)) => Int =  x =>(x._1 + x._2)
val g: (Int, Int) => Int = Function.untupled(h)
val f : Int => Int => Int = g.curried  //Function.curried(g) would also work, but is deprecated. Wierd
like image 37
Dave Griffith Avatar answered Sep 22 '22 01:09

Dave Griffith