While Loop Macro in DrRacket

前端 未结 4 1503
野性不改
野性不改 2020-12-11 20:49

I am trying to create a macro for while loop in DrRacket. Here is what I wrote:

(require mzlib/defmacro)

(define-macro my-while
  (lambda (condition  body)
         


        
4条回答
  •  感动是毒
    2020-12-11 21:51

    Ouch:

    1. Using this style of while loop encourages excessive use of imperative programming.
    2. Using define-macro creates unhygienic macros, which is a nightmare in Scheme.

    While I don't encourage writing an imperative-style loop macro, for your reference, here's a non-define-macro version of the same macro:

    (define-syntax-rule (my-while condition body ...)
      (let loop ()
        (when condition
          body ...
          (loop))))
    

    It uses syntax-rules, which creates hygienic macros, and is much, much easier to read than what you have.


    Now, for the actual answer for your question, first, let's write your original macro out in a more readable way:

    (define-macro my-while
      (lambda (condition body)
        `(local ((define (while-loop)
                   (if ,condition
                       (,body (while-loop))
                       (void))))
           (while-loop))))
    

    Once you write it out this way, you can see where the real problem is: in the (,body (while-loop)) line, which should instead have been (begin ,body (while-loop)).

提交回复
热议问题