Scala用函数参数进行currying

时间:2014-04-27 14:13:01

标签: scala

我正在学习scala中的currying,并尝试将我的知识应用于以下代码。

object excercise {

  def sqrt2(input : Double) : ((Double, Double) => Double, Double) => Double = {
    def iter(guessFxn : (Double, Double) => Double, initial : Double) : Double = {
      if (isGoodEnough(initial)) initial
      else {
        val newGuess: Double = guessFxn(initial, input)
        iter(guessFxn, newGuess)
      }
    }

    iter

    def isGoodEnough(guess: Double): Boolean = {
      math.abs(guess * guess - input ) / input < 0.001
    }

  }
  println(sqrt2(2) ( (g: Double, c: Double) => (g + c / g) / 2, 1))

}

我想要实现的是sqrt2应该返回一个带有2个参数的函数 1. fxn(需要2个双精度作为arg并返回双重值)
2. double val

当我试图运行工作表时,它给了我错误

Error: missing arguments for method iter;
follow this method with `_' if you want to treat it as a partially applied function
    iter
    ^
Error: type mismatch;
 found   : Unit
 required: ((Double, Double) => Double, Double) => Double
  }
  ^
Error: missing arguments for method iter;
follow this method with `_' if you want to treat it as a partially applied function
    iter
    ^

1 个答案:

答案 0 :(得分:3)

你只需要颠倒那些代码的顺序:

iter

def isGoodEnough(guess: Double): Boolean = {
   math.abs(guess * guess - input ) / input < 0.001
}

变为:

def isGoodEnough(guess: Double): Boolean = {
   math.abs(guess * guess - input ) / input < 0.001
}

iter 

实际上,以内部声明的方法结束涉及返回类型Unit ......这不是你想要的。

此外,你有这个建议:

follow this method with `_' if you want to treat it as a partially applied function
    iter

因为如前所述,不返回iter方法(因为它的调用不是在方法结束时进行的),因此编译器希望它被执行。
当然,要执行,它需要你没有提供的强制参数 所以编译器“认为”你希望部分应用这个功能但是很糟糕。注意部分应用功能与部分功能的概念不同,具有不同的含义......)。
它允许延迟调用,它主要用于处理标准函数(不是curried),我们可能只需要提供第一个参数,然后再提供以下参数。

部分应用功能的示例:

def sum(i: Int, j: Int){...}

调用:

sum 1 _ //just the second parameter needs to be applied later.
sum _  //none parameter is specified, would need to specify both later.
sum 1 2 //complete call, not partially applied so

您可以找到部分应用函数here的良好用例。

相关问题