我正在尝试修改 SICP 中的这段代码:
(define (whatever x y)
(newline)
(display "called with ")
(display x)
(if (> x y)
0 ; if x <= y, return 0 and skip the rest
(+ x (whatever (+ 1 x) y))))
我想要做的是在“其余”中添加一行,打印出在 返回值。例如,现在我的
(whatever 1 5)
输出给出:
called with 1
called with 2
called with 3
called with 4
called with 5
called with 6
;Value: 15
我希望它能够给出:
called with 1 returning 15
called with 2 returning 14
called with 3 returning 12
called with 4 returning 9
called with 5 returning 5
called with 6 returning 0
;Value: 15
我尝试的所有操作要么告诉我语法错误,要么说“object
#!unspecific
”是错误的类型。我明白为什么我会收到这些错误(即函数想要返回一个数字,但 (display (+ x (whatever (... )))
没有返回正确类型的值)。
(define...
0
(display (+ x (whatever (+ x 1) y))))
给出错误消息,指出对象
#!unspecific
类型错误
如果我将其更改为
(define...
0
(display (+ x (whatever (+ x 1) y))))
(+ x (whatever (+ x 1) y))))
给出了格式不正确的语法错误,在双重和三次检查我的括号嵌套后我无法摆脱该错误。
如果我取出
(display ... )
,它就会按预期工作。
有人愿意向我展示一种精益的方法来获得我想要的输出吗?
在递归返回之前你无法打印结果,所以如果你先打印参数,
(define (whatever x y)
(display "called with ")
(display x)
(newline)
(if (> x y)
(begin
(display "returning 0")
(newline)
0)
(begin
(let ((result (+ x (whatever (+ 1 x) y))))
(display "returning ")
(display result)
(newline)
result))))
输出为:
> (whatever 1 5)
called with 1
called with 2
called with 3
called with 4
called with 5
called with 6
returning 0
returning 5
returning 9
returning 12
returning 14
returning 15
15
如果您希望参数和结果位于同一行,则它们最终会以其他顺序
(define (whatever x y)
(if (> x y)
(begin
(display "called with ")
(display x)
(display " returning 0")
(newline)
0)
(begin
(let ((result (+ x (whatever (+ 1 x) y))))
(display "called with ")
(display x)
(display " returning ")
(display result)
(newline)
result))))
输出
> (whatever 1 5)
called with 6 returning 0
called with 5 returning 5
called with 4 returning 9
called with 3 returning 12
called with 2 returning 14
called with 1 returning 15
15
如果你想颠倒顺序,事情就会变得更复杂。