define-syntax issue in scheme

孤人 提交于 2019-12-11 04:29:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!