[scala] 如何將函數應用於元組?


Answers

跟進另一個答案,可以寫(用2.11.4測試):

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 p = (3,4)
p: (Int, Int) = (3,4)

scala> ff.tupled(p)
res0: Int = 7

def tupled:((T1,T2))⇒R

創建此函數的tupled版本:它接受單個scala.Tuple2參數,而不是2個參數。

Question

這應該是一個簡單的。 如何將函數應用於Scala中的元組? 即:

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!

提前謝謝了。




Related



Tags

scala scala