Question

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?

Was it helpful?

Solution

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

scala> Function.uncurried(f)
res0: (Int, Int) => Int = <function2>

OTHER TIPS

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

Just to round out the answer, although there is a library method to do this, it may also be instructive to do it by hand:

scala> val f = (i: Int) => ((s: String) => i*s.length)
f: (Int) => (String) => Int = <function1>

scala> val g = (i: Int, s: String) => f(i)(s)
g: (Int, String) => Int = <function2>

Or in general,

def uncurry[A,B,C](f: A=>B=>C): (A,B)=>C = {
  (a: A, b: B) => f(a)(b)
}

Similar to the answer by Rex Kerr but easier to read.

type A = String
type B = Int
type C = Boolean

val f: A => B => C = s => i => s.toInt+i > 10

val f1: (A, B) => C = f(_)(_)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top