【发布时间】:2011-01-02 08:17:29
【问题描述】:
我一直在与 The Little Schemer 一起学习 Scheme 并在我的环境中使用 PLT-Scheme。
The Little Schemer 极大地帮助了我的递归(现在对我来说很简单),但我被困在书中介绍“收集器”并将函数作为一个整体调用的部分继续。
这是他们使用的示例代码。我理解递归元素,但我被困住了,特别是在 lambda 函数上——我的头脑无法遵循路径以及该 lambda 函数的参数是如何设置的(因为它们唯一的调用是在递归中再次调用它们,所以有在函数体内没有具体的使用)。
如果有人可以通过将函数递归到 lambda 收集器中或多或少地给我分解计算路径,那可能会对我有所帮助。
;; Build a nested list of even numbers by removing the odd ones from its
;; argument and simultaneously multiply the even numbers and sum the odd
;; numbers that occur in its argument.
(define (even-only-collector l col)
(cond
((null? l)
(col (quote ()) 1 0))
((atom? (car l))
(cond
((even? (car l))
(even-only-collector (cdr l)
(lambda (newl p s)
(col (cons (car l) newl)
(* (car l) p) s))))
(else
(even-only-collector (cdr l)
(lambda (newl p s)
(col newl
p (+ (car l) s)))))))
(else
(even-only-collector (car l)
(lambda (al ap as)
(even-only-collector (cdr l)
(lambda (dl dp ds)
(col (cons al dl)
(* ap dp)
(+ as ds)))))))))
;; The collector function
(define (collector newl product sum)
(cons sum
(cons product newl)))
提前谢谢你!!
【问题讨论】:
-
@lpthnc:你看过 newLISP 吗?
标签: scheme lisp racket continuations the-little-schemer