tags:

views:

574

answers:

2

This should be an easy one. How do I apply a function to a tuple in Scala? Viz:

scala> def f (i : Int, j : Int) = i + j
f: (Int,Int)Int

scala> val p = (3,4)
p: (Int, Int) = (3,4)

scala> f p
:6: error: missing arguments for method f in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       f p
       ^

scala> f _ p
:6: error: value p is not a member of (Int, Int) => Int
       f _ p
           ^

scala> (f _) p
:6: error: value p is not a member of (Int, Int) => Int
       (f _) p
             ^

scala> f(p)
:7: error: wrong number of arguments for method f: (Int,Int)Int
       f(p)
       ^

scala> grr!

Many thanks in advance.

+2  A: 

Your function doesn't accept a tuple, it accepts two Ints. To call this function with your tuple, use ._1 and ._2

f(p._1, p._2)
Adam Sills
+9  A: 

In Scala 2.7:

scala> def f (i : Int, j : Int) = i + j
f: (Int,Int)Int

scala> val ff = f _
ff: (Int, Int) => Int = <function>

scala> val fft = Function.tupled(ff)
fft: ((Int, Int)) => Int = <function>

In Scala 2.8:

scala> def f (i : Int, j : Int) = i + j
f: (i: Int,j: Int)Int

scala> val ff = f _
ff: (Int, Int) => Int = <function2>

scala> val fft = ff.tuple
fft: ((Int, Int)) => Int = <function1>
Randall Schulz
Typo - the last line for both 2.7 and 2.8 should be ff.tupled, not ff.tuple
James Moore