为什么柯里化不适用于函数字面量?
why currying does not work with a function literal?
第一种形式有效而第二种形式无效的逻辑原因是什么?
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
因为函数声明中不允许使用多个参数列表。如果你想柯里化一个函数,你可以这样做:
scala> val d: Int => Int => Int = a => b => a + b
d: Int => (Int => Int) = $$Lambda06/512934838@6ef4cbe1
scala> val f = d(3)
f: Int => Int = $$Lambda09/1933965693@7e2c6702
scala> f(4)
res6: Int = 7
您还可以创建单个参数列表并部分应用它:
scala> val d = (a: Int, b: Int) => a + b
d: (Int, Int) => Int = $$Lambda64/586164630@7c8874ef
scala> d(4, _: Int)
res2: Int => Int = $$Lambda79/2135563436@4a1a412e
我们用 4 部分应用了 d
,我们得到了一个函数,Int => Int
,这意味着当我们提供下一个参数时,我们将得到结果:
scala> res2(3)
res3: Int = 7
我们还可以创建一个命名方法,并使用 eta 扩展从中创建一个柯里化函数:
scala> def add(i: Int)(j: Int): Int = i + j
add: (i: Int)(j: Int)Int
scala> val curriedAdd = add _
curriedAdd: Int => (Int => Int) = $$Lambda15/287609100@f849027
scala> val onlyOneArgumentLeft = curriedAdd(1)
onlyOneArgumentLeft: Int => Int = $$Lambda16/1700143613@77e9dca8
scala> onlyOneArgumentLeft(2)
res8: Int = 3
函数柯里化是可能的。
val curryFunc = (a: Int) => (b: Int) => a + b
curryFunc 现在的类型是 Int => (Int => Int)
第一种形式有效而第二种形式无效的逻辑原因是什么?
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
因为函数声明中不允许使用多个参数列表。如果你想柯里化一个函数,你可以这样做:
scala> val d: Int => Int => Int = a => b => a + b
d: Int => (Int => Int) = $$Lambda06/512934838@6ef4cbe1
scala> val f = d(3)
f: Int => Int = $$Lambda09/1933965693@7e2c6702
scala> f(4)
res6: Int = 7
您还可以创建单个参数列表并部分应用它:
scala> val d = (a: Int, b: Int) => a + b
d: (Int, Int) => Int = $$Lambda64/586164630@7c8874ef
scala> d(4, _: Int)
res2: Int => Int = $$Lambda79/2135563436@4a1a412e
我们用 4 部分应用了 d
,我们得到了一个函数,Int => Int
,这意味着当我们提供下一个参数时,我们将得到结果:
scala> res2(3)
res3: Int = 7
我们还可以创建一个命名方法,并使用 eta 扩展从中创建一个柯里化函数:
scala> def add(i: Int)(j: Int): Int = i + j
add: (i: Int)(j: Int)Int
scala> val curriedAdd = add _
curriedAdd: Int => (Int => Int) = $$Lambda15/287609100@f849027
scala> val onlyOneArgumentLeft = curriedAdd(1)
onlyOneArgumentLeft: Int => Int = $$Lambda16/1700143613@77e9dca8
scala> onlyOneArgumentLeft(2)
res8: Int = 3
函数柯里化是可能的。
val curryFunc = (a: Int) => (b: Int) => a + b
curryFunc 现在的类型是 Int => (Int => Int)