我无法弄清楚 DrRacket(IDE)抱怨的关于
(define (bifurcate f a f_a b f_b)...
的问题,请指教。据说定义块是一个不正确的表达式,并且可能是一个隐式的开始。
请注意,如果我将定义复制并粘贴到 REPL 窗口中(当然,还定义了 f_a、f_b 等),则它可以正常工作。非常感谢! #lang racket
;function to return root of y = f(x) where we know solution is in some bracket [a, b]
;subject to a < b and
;sign(f(a)) != sign(f(b))
;
;my version of "search" on pg 67 "Structure and Interpretation of Computer Programs"
;
(define (bifurcate-wrapper f a b)
(if (or (positive? (* (f a) (f b))) (>= a b)) ;check for erroneous input
#f
(let ((f_a (f a)) (f_b (f b))); initial values, don't recalculate BOTH f(a) and f(b) ea. time
(define (bifurcate f a f_a b f_b); DrRacket says this define is not an expression...
(let ((midpoint (/ (+ a b) 2.0)))
(if (close-enough? a b)
midpoint
(let ((f_mid (f midpoint)))
(cond ((positive? (* f_a f_mid))
(bifurcate f midpoint f_mid b f_b))
((positive? (* f_mid f_b))
(bifurcate f a f_a midpoint f_mid))
(else midpoint)))))); end of define
)
)
)
(define (close-enough? x y)
(< (abs (- x y)) 0.001))
(bifurcate-wrapper sin 2.0 4.0) ;expect pi
完整的错误消息是
49-unsaved-editor:7:8: begin (possibly implicit): the last form is not an expression
at: (define (bifurcate f a f_a b f_b) (let ((midpoint (/ (+ a b) 2.0))) (if (close-enough? a b) midpoint (let ((f_mid (f midpoint))) (cond ((positive? (* f_a f_mid)) (bifurcate f midpoint f_mid b f_b)) ((positive? (* f_mid f_b)) (bifurcate f a f_a mid...
in: (begin (define (bifurcate f a f_a b f_b) (let ((midpoint (/ (+ a b) 2.0))) (if (close-enough? a b) midpoint (let ((f_mid (f midpoint))) (cond ((positive? (* f_a f_mid)) (bifurcate f midpoint f_mid b f_b)) ((positive? (* f_mid f_b)) (bifurcate f a ...
#(242 502)
那是因为外部
let
主体中唯一的东西是binfurcate
的定义,而define
是scheme和Racket中为数不多的不是表达式之一。 let
允许 0 个或多个内部 define
后跟表达式(可能与更多内部定义混合,但必须以表达式结尾)。
您只需在定义后调用您的
bifurcation
函数即可满足该要求。我还会清理你的缩进(DrRacket 中的Racket菜单 -> Reindent All)并移动所有这些单行结束括号,以便它们以正常的 Lispy 风格与其余部分拥抱在一起。
对于解决 SICP 问题,还可以考虑安装 SICP 包 并使用
#lang sicp
。这提供了本书假设的主机方案中存在但标准 Racket 中不存在的一些内容。