2017-07-18 107 views
2

第一種形式起作用的邏輯原因是什麼,而不是第二種?爲什麼currying不能與函數字面值一起使用?

scala> val d = (a: Int, b: Int) => a + b 
d: (Int, Int) => Int = <function2> 

scala> val d = (a: Int)(b: Int) => a + b 

<console>:1: error: not a legal formal parameter. 
Note: Tuples cannot be directly destructured in method or function parameters. 
Either create a single parameter accepting the Tuple1, 
or consider a pattern matching anonymous function: `{ case (param1, param1) => ... } 
val d=(a:Int)(b:Int)=>a+b 
+2

'VAL d =(A:強度)=>(B:強度)=>一個+ B' – jwvh

回答

3

因爲在函數聲明中不允許多個參數列表。如果你想討好的功能,你這樣做:

scala> val d: Int => Int => Int = a => b => a + b 
d: Int => (Int => Int) = $$Lambda$1106/[email protected] 

scala> val f = d(3) 
f: Int => Int = $$Lambda$1109/[email protected] 

scala> f(4) 
res6: Int = 7 

您還可以創建一個單一的參數列表和部分應用它:

scala> val d = (a: Int, b: Int) => a + b 
d: (Int, Int) => Int = $$Lambda$1064/[email protected] 

scala> d(4, _: Int) 
res2: Int => Int = $$Lambda$1079/[email protected] 

我們部分有4個應用d,我們得到了回來功能,Int => Int,這意味着當我們提供一個參數,我們得到的結果:

scala> res2(3) 
res3: Int = 7 

我們也可以創建一個命名的方法,並使用ETA-EXP ansion創建一個咖喱功能:

scala> def add(i: Int)(j: Int): Int = i + j 
add: (i: Int)(j: Int)Int 

scala> val curriedAdd = add _ 
curriedAdd: Int => (Int => Int) = $$Lambda$1115/[email protected] 

scala> val onlyOneArgumentLeft = curriedAdd(1) 
onlyOneArgumentLeft: Int => Int = $$Lambda$1116/[email protected] 

scala> onlyOneArgumentLeft(2) 
res8: Int = 3 
1

功能咖喱是可能的。

val curryFunc = (a: Int) => (b: Int) => a + b 

curryFunc現在具有類型Int => (Int => Int)

相關問題