调用curried函数

时间:2015-03-28 14:13:25

标签: scala

以下是curried函数的实现:

scala> def multiply(x: Int, y: Int) = x * y
multiply: (x: Int, y: Int)Int

scala> def multiplyCurried = (multiply _).curried
multiplyCurried: Int => (Int => Int)

当我尝试实现multiplyCurried时,我收到异常:

<console>:10: error: missing parameter type
              multiplyCurried(a => b => a * b)

调用multiplyCurried的正确实现是什么?

1 个答案:

答案 0 :(得分:1)

来自维基百科:Currying是一种将多个参数(或参数元组)的函数的评估转换为评估函数序列的技术,每个函数都有一个参数(部分应用程序)

def multiply(x: Int, y: Int) = x * y          //> multiply: (x: Int, y: Int)Int

def multiplyCurried = (multiply _).curried    //> multiplyCurried: => Int => (Int => Int)

def multiplyCurried2(x: Int)(y: Int) = x * y  //> multiplyCurried2: (x: Int)(y: Int)Int

def multiplyCurried3(x:Int) = (y:Int) => x * y //> multiplyCurried3: (x: Int)Int => Int

def multiplyCurried4 = multiplyCurried2 _ //> multiplyCurried4: => Int => (Int => Int)

multiply(1, 2)                                //> res1: Int = 2
multiplyCurried(1)(2)                         //> res2: Int = 2
multiplyCurried2(1)(2)                        //> res3: Int = 2
multiplyCurried3(1)(2)                        //> res4: Int = 2

multiplyCurried2只是multiplyCurried3的语法糖。

正如Victor在评论中正确指出的那样,multiplyCurriedmultiplyCurried2实际上并不相同。 multiplyCurried4的实施包含将multiplyCurried2转换为基本上等于multiplyCurried的函数的方法。

关于currying的好处是部分应用:

val m = multiplyCurried(1)                    //> m  : Int => Int = <function1>
m(2)                                           //> res5: Int = 2
val m2 = multiplyCurried2(1)_                 //> m  : Int => Int = <function1>
m2(2) 

                                    //> res6: Int = 2