0
我正在嘗試使用SICP學習Scala,但是我很難用函數的類型定義並卡在SICP。這裏廣義表達是構建的,其中代替尋找一個數的平方根(通過定點搜索或牛頓法):接受函數的函數中參數的類型
def sqrt_damp(x: Double) =
fixed_point(average_damp(y => x/y))(1)
def sqrt_newton(x: Double) =
fixed_point(newton_method(y => square(y) - x))(1)
基於該功能:
def square(x: Double) = x * x
def average(x: Double, y: Double) = (x + y)/2
def abs(x: Double) = if (x < 0) -x else x
val tolerance = 0.00001
def fixed_point(f: Double => Double)(first_guess: Double) = {
def close_enough(v1: Double, v2: Double): Boolean = abs(v1 - v2) < tolerance
def attempt(guess: Double): Double = {
val next = f(guess)
if (close_enough(guess, next)) next else attempt(next)
}
attempt(first_guess)
}
def average_damp(f: Double => Double): Double => Double =
x => average(x, f(x))
val dx = 0.00001
def deriv(g: Double => Double): Double => Double =
x => (g(x + dx) - g(x))/dx
def newton_transform(g: Double => Double): Double => Double =
x => x - g(x)/deriv(g)(x)
def newton_method(g: Double => Double)(guess: Double): Double =
fixed_point(newton_transform(g))(guess)
的平方函數
(define (fixed-point-of-transform g transform guess)
(fixed-point (transform g) guess))
其中我試圖表達在斯卡拉如下:可以在形式廣義
def fixed_point_of_transform(g: Double => Double, transform: Double => Double)(guess: Double): Double =
fixed_point(transform(g))(guess)
然而,上述不編譯並生成錯誤
type mismatch; found : Double => Double required: Double
編輯,以下工作:
def fixed_point_of_transform(g: Double => Double, transform: (Double => Double) => (Double => Double))(guess: Double): Double =
fixed_point(transform(g))(guess)
所以現在前面的功能可以被定義爲:
def sqrt_damp(x: Double) =
fixed_point_of_transform(y => x/y, average_damp)(1)
def sqrt_newton(x: Double) =
fixed_point_of_transform(y => square(y) - x, newton_method)(1)
我想我現在明白了,所以我應該做'transform:(Double => Double)=>(Double => Double)' – nzn