Macros are expanded at compile time, thus something like (begin exps ... (forloop (+ start 1) stop exps ...))
will expand forloop
again and again, regardless of what the value of (+ start 1)
is (which is evaluated at runtime).
Perhaps the best you can do, at least with syntax-rules
, is to use the macro to capture only the expressions to run, and use non-macro code to deal with the looping:
(define-syntax forloop
(syntax-rules ()
((forloop start stop exps ...)
(let ((j stop))
(let loop ((i start))
(when (<= i j)
exps ...
(loop (+ i 1))))))))
You can also use a do
loop:
(define-syntax forloop
(syntax-rules ()
((forloop start stop exps ...)
(let ((j stop))
(do ((i start (+ i 1)))
((> i j))
exps ...)))))