在阅读“经验丰富的计划者”时,我开始了解letrec
. 我理解它的作用(可以用 Y-Combinator 复制),但本书使用它来代替在已经define
d 函数上重复运行,该函数对保持静态的参数进行操作。
一个使用define
d 函数的旧函数的例子(没有什么特别的):
(define (substitute new old l)
(cond
((null? l) '())
((eq? (car l) old)
(cons new (substitute new old (cdr l))))
(else
(cons (car l) (substitute new old (cdr l))))))
现在举一个相同功能的例子,但使用letrec
:
(define (substitute new old l)
(letrec
((replace
(lambda (l)
(cond
((null? l) '())
((eq? (car l) old)
(cons new (replace (cdr l))))
(else
(cons (car l) (replace (cdr l))))))))
(replace lat)))
除了略长且更难阅读之外,我不知道他们为什么要重写书中的函数以使用 letrec。以这种方式重复静态变量时是否会提高速度,因为您不会一直传递它?
对于具有保持静态但减少了一个参数(例如递归列表的元素)的函数,这是标准做法吗?
来自更有经验的计划者/LISPers 的一些输入会有所帮助!