最近在学习 scheme 中的 continuation,终于把 tree-generator(Teach Yourself Scheme in Fixnum Days) 看懂了,根据自己的理解又写了一个改良版本,比较容易理解。
;;; Function: tree->generator
;;; Example:
;;; > (define t '(1 (2) 3))
;;; > (define gen (tree->generator t))
;;; > (gen)
;;; 1
;;; > (gen)
;;; 2
;;; > (gen)
;;; 3
;;; > (gen)
;;; '()
;;; > (gen)
;;; '()
(define (tree->generator tree)
(let ((leaf #f) (walk-tree #f))
(define (walk-tree)
(let loop ((tree tree))
(cond ((null? tree) 'skip)
((pair? tree) (loop (car tree))
(loop (cdr tree)))
(else (call/cc
(lambda (rest-of-tree)
(set! walk-tree
(lambda ()
(rest-of-tree 'resume)))
(leaf tree))))))
(leaf '()))
(define (next)
(call/cc
(lambda (k)
(set! leaf k)
(walk-tree))))
next))
阅读(1190) | 评论(1) | 转发(0) |