我在工作表中运行以下 Scala 代码:
package src.com.sudipta.week2.coursera
import scala.math.abs
import scala.annotation.tailrec
object FixedPoint {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
val tolerance = 0.0001 //> tolerance : Double = 1.0E-4
def isCloseEnough(x: Double, y: Double): Boolean = {
abs((x - y) / x) / x < tolerance
} //> isCloseEnough: (x: Double, y: Double)Boolean
def fixedPoint(f: Double => Double)(firstGuess: Double): Double = {
@tailrec
def iterate(guess: Double): Double = {
val next = f(guess)
if (isCloseEnough(guess, next)) next
else iterate(next)
}
iterate(firstGuess)
} //> fixedPoint: (f: Double => Double)(firstGuess: Double)Double
def myFixedPoint = fixedPoint(x => 1 + x / 2)(1)//> myFixedPoint: => Double
myFixedPoint //> res0: Double = 1.999755859375
def squareRoot(x: Double) = fixedPoint(y => (y + x / y) / 2)(1)
//> squareRoot: (x: Double)Double
squareRoot(2) //> res1: Double = 1.4142135623746899
def calculateAverate(f: Double => Double)(x: Double) = (x + f(x)) / 2
//> calculateAverate: (f: Double => Double)(x: Double)Double
def myNewSquareRoot(x: Double): Double = fixedPoint(calculateAverate(y => x / y))(1)
//> myNewSquareRoot: (x: Double)Double
myNewSquareRoot(2) //> res2: Double = 1.4142135623746899
}
让我感到困惑的是:
- 下面显示了我的 fixedPoint 函数的 Scala 工作表
fixedPoint: (f: Double => Double)(firstGuess: Double)Double
这是什么?这是函数类型/函数定义还是我错过了这个术语?基本上我怎么能用英语解释这个功能?
- 下面显示了我的 calculateAverate 函数的 Scala 工作表
calculateAverate: (f: Double => Double)(x: Double)Double
但在我看来,我的函数的返回类型是 Double,但我期待 Double => Double。原因是我打算将它与期望 Double => Double 的 fixedPoint 一起使用,如下所示:
def myNewSquareRoot(x: Double): Double = fixedPoint(calculateAverate(y => x / y))(1)
请帮助我更清楚地理解高阶函数/柯里化。提前致谢。