解释一些使用递归和currying的代码

时间:2012-10-25 09:49:43

标签: scala

此代码中的方法产品如何使用?

此功能的结果为3600

因此产品具有以下功能:f, f采用Int参数返回Int参数。

但是(a:Int,b:Int)是否表示返回带有两个Int参数的函数?

我对此行中发生的事情感到困惑: f(a)* product(f)(a + 1,b)

完成功能:

 def product(f: Int => Int)(a: Int, b: Int): Int =
    if(a > b) 1
    else {
     f(a) * product(f)(a + 1, b)
    }                                        
  product(x => x * x)(3 , 5)  

1 个答案:

答案 0 :(得分:4)

在Scala中,方法可以有多个参数列表。在此示例中,方法product有两个参数列表:(f: Int => Int)(a: Int, b: Int)

第一个参数列表包含一个名为f的参数,该参数的类型为Int => Int(一个带Int并返回Int的函数。)

第二个参数列表包含两个名为ab的参数,它们都是Int类型。

表达式product(f)(a + 1, b)product(x => x * x)(3 , 5)只需使用所有三个参数调用该方法。

这样做的好处是你可以只用第一个参数列表“调用”product。您将获得的是一个可以通过提供第二个参数列表来调用的函数。例如:

val fn = product(x => x * x)  // only the first parameter list is applied
fn(3, 5)                 // fn is a function which you can pass the second list

仅使用第一个参数列表“呼叫”product称为 currying