首页 > 代码库 > 为scheme添加for循环语句

为scheme添加for循环语句

有三个辅助关键字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
因为要捕捉可能的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* ...))))))))))))

为scheme添加for循环语句