问题
I'm wondering what is going wrong with how I'm defining my for-loop in scheme. Whenever I try running a for statement with it it runs for quite a while and then crashes.
(define-syntax for
(syntax-rules (:)
[(_ (initial : test : update) body)
(begin initial
(if test
(begin body update
(for [test : update] body))))]
[(_ (test : update) body)
(if test
(begin body update
(for [test : update] body)))]))
It should run the initial condition, check the test, run the body, and then loop to the next run.
回答1:
Your macro fails because the macro is recursive and there is no base case. Thus during compilation, the macro expands, and expands again, and expands again, forever.
Here is an implementation:
(define-syntax for
(syntax-rules (:)
((_ (initial : test : update) body)
(begin initial
(let repeating ()
(when test
body
update
(repeating)))))
((_ (test : update) body)
(for (#f : test : update) body))))
> (let ((foo 0))
(for ((set! foo 5) : (positive? foo) : (set! foo (- foo 1))) ;; w/ init
(begin (display 'YES) (newline))))
YES
YES
YES
YES
YES
> (let ((foo 2))
(for ((positive? foo) : (set! foo (- foo 1))) ;; w/o init
(begin (display 'YES) (newline)))
YES
YES
来源:https://stackoverflow.com/questions/16205002/define-syntax-issue-in-scheme