首页 > 代码库 > 为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循环语句
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。