有三个辅助关键字in, from和to
能够 break和continue
语法有三种
(for n in '(1 2 3 4 5 6 7 8 9 10)
(if (> n 8) (break #f))
(if (even? n) (continue #f))
(display n)
(display " "))
=> 1 3 5 7 #f
(for n from 1 to 100
(if (> n 10) (break #f))
(display n)
(display " "))
=> 1 2 3 4 5 6 7 8 9 10 #f
(for n from 100 99 to 1
(if (< n 90) (break #f))
(display n)
(display " "))
=> 100 99 98 97 96 95 94 93 92 91 90 #f
(define (product nums)
(define p 1)
(for n in nums
(when (zero? n)
(set! p 0)
(break #f))
(set! p (* p n)))
p)
(product '(1 2 3 0 2)) ;=> 0
(product '(1 2 3 2)) ;=> 12
因为要捕捉可能的break和continue,用syntax-case编写。
(define-syntax for (lambda (x) (syntax-case x (in from to) ((k e in l c c* ...) (with-syntax ((break (datum->syntax (syntax k) 'break)) (continue (datum->syntax (syntax k) 'continue))) (syntax (call/cc (lambda (break) (do ((ns l (cdr ns))) ((null? ns)) (let ((e (car ns))) (call/cc (lambda (continue) c c* ...))))))))) ((k i from a to z c c* ...) (with-syntax ((break (datum->syntax (syntax k) 'break)) (continue (datum->syntax (syntax k) 'continue))) (syntax (let ((a* a) (z* z)) (call/cc (lambda (break) (do ((i a* (+ i 1))) ((> i z*)) (call/cc (lambda (continue) c c* ...))))))))) ((k i from a b to z c c* ...) (with-syntax ((break (datum->syntax (syntax k) 'break)) (continue (datum->syntax (syntax k) 'continue))) (syntax (let* ((a* a) (b* b) (z* z) (s (- b* a*)) (p (if (> b* a*) > <))) (call/cc (lambda (break) (do ((i a* (+ i s))) ((p i z*)) (call/cc (lambda (continue) c c* ...))))))))))))
转载于:https://www.cnblogs.com/billythekid/p/4014117.html