我正在尝试使用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))
我试图在Scala中表达如下:
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)
答案 0 :(得分:1)
transform
需要Double
并返回Double
。您无法将其应用于g
,因为g
是一个函数Double => Double
。您可以将其应用于g(x)
,x: Double
。我想这就是你想要的:fixed_point((x: Double) => transform(g(x)))(guess)