1

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.

GoZoner
  • 67,920
  • 20
  • 95
  • 145
Ian Hallam
  • 11
  • 2

1 Answers1

3

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
GoZoner
  • 67,920
  • 20
  • 95
  • 145