(define (myminus x y)
(cond ((zero? y) x)
(else (sub1 (myminus x (sub1 y))))))
(define (myminus_v2 x y)
(cond ((zero? y) x)
(else (myminus_v2 (sub1 x) (sub1 y)))))
请根据每个递归调用在堆栈上需要多少内存来评论这些函数之间的差异。另外,您可能希望哪个版本更快,为什么?
谢谢!
(define (myminus x y)
(cond ((zero? y) x)
(else (sub1 (myminus x (sub1 y))))))
(define (myminus_v2 x y)
(cond ((zero? y) x)
(else (myminus_v2 (sub1 x) (sub1 y)))))
请根据每个递归调用在堆栈上需要多少内存来评论这些函数之间的差异。另外,您可能希望哪个版本更快,为什么?
谢谢!
They should both have a number of steps proportional to y.
The second one is a tail call meaning the interpreter can do a tail elimination meaning it takes up a constant space on the stack whereas in the first the size of the stack is proportional to Y.
myminus
创建递归计算结果的y
延续。sub1
这意味着您可以耗尽球拍内存限制,使程序失败。在我的试验中,即使使用DrRacket中的标准 128MB 限制,即使只有 1000 万也不会成功。
myminus_v2
是tail recursive
并且由于racket
具有与所需相同的属性scheme
,尾调用将被优化为 goto 而不会增长堆栈,y 可以是任何大小,即只有您的可用内存和处理能力是大小的限制。
你的程序是皮亚诺算术的好例子。