对于调试,我想在具有显式返回类型的函数中使用println

时间:2014-08-02 13:14:29

标签: scala

我一直收到错误:type mismatch: found Uint required Double

当我在println方法中放置sqrt函数时。虽然我很欣赏它的部分Scala防止副作用,但是如何在函数中打印值以便我能理解我的程序?是否有一种“干净”的方法在需要显式返回类型的函数中打印值(如递归函数sqrt)?

代码在这里:

object Newton {

    def threshold(guess: Double, x: Double) : Boolean = 
        if (Math.abs(guess * guess -x) < (0.01/100 * x)) true else false

    def improve(guess: Double, x: Double) : Double =
         (guess + x/guess) / 2.0

    def sqrt(guess: Double, x: Double, 
        threshold: (Double, Double) => Boolean,
        improve: (Double, Double) => Double ): Double = 
        println("current guess:", guess)
        if(threshold(guess,x)) 
            return guess
        else
            return sqrt(improve(guess, x), x, threshold, improve)

    def main(args: Array[String]): Unit = {
      println("Sqrt of Two:", sqrt(1,1.0e-20,threshold, improve))
    }
}

1 个答案:

答案 0 :(得分:2)

你缺少大括号。

def sqrt(guess: Double, x: Double, 
         threshold: (Double, Double) => Boolean,
         improve: (Double, Double) => Double ): Double = { // Add curly braces

    println("current guess:", guess)
    if(threshold(guess,x)) 
       return guess
    else
       return sqrt(improve(guess, x), x, threshold, improve)

} // Add curly braces