2017-07-18 10 views
2

最初のフォームが機能し、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

'ヴァルさd =(:INT)=>(B:INT)=> A + 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 
あなたはまた、単一のパラメータリストを作成し、部分的にそれを適用することができ

:我々は、部分的に4でdを適用し、我々は戻った

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] 

私たちは次の引数を指定するとき、我々は結果を得るでしょう意味機能、 Int => Int、:

scala> res2(3) 
res3: Int = 7 

我々はまた、名前のメソッドを作成し、ETA-EXPを使用することができますそれからカレー化された機能を作り出すための陰謀:

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)

関連する問題