2017-07-18 60 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)

相关问题