2010-01-01 118 views
39

這應該是一個容易的。我如何將函數應用於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! 

非常感謝提前。

回答

55

在斯卡拉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> 

在斯卡拉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.tupled 
fft: ((Int, Int)) => Int = <function1> 
+1

值得注意,斯卡拉(2.11.0這裏)將帶給您untupled PARAMS到一個元組,如果你這樣做:'fft.apply(1,2)' – ThaDon 2014-09-11 12:57:23

+0

好知道你可以做到這一點,但這似乎並不比僅僅使用'function(tup._1,tup._2)'更簡短 – 2016-10-10 23:40:00

+3

@AllenWang我認爲重要的一點是'tupled'可以用於任何參數。良好的可維護性。 – Ohashi 2016-11-01 02:42:59

8

對對方的回答跟進,一個可以寫(與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

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

0
scala> def f (i: Int, j: Int) = i + j 
f: (i: Int, j: Int)Int 
scala> val p = (3,4) 
p: (Int, Int) = (3,4) 
scala> val ft = (f _).tupled 
ft: ((Int, Int)) => Int = <function1> 
scala> ft apply(p) 
res0: Int = 7 
相關問題