help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Compiling a recursive macro


From: Jakub Jankiewicz
Subject: Re: Compiling a recursive macro
Date: Sat, 13 Jun 2020 15:34:06 +0200

> BTW2, a small problem with your posted version is that it adds one `let'
> binding per branch, but only the outermost is needed:

Thanks I've fixed my macro now it looks like this:

(define-macro (case val . list)
  "(case value
        ((<items>) result1)
        ((<items>) result2)
        [else result3])

   Macro for switch case statement. It test if value is any of the item. If
   item match the value it will return coresponding result expression value.
   If no value match and there is else it will return that result."
  (let ((value (gensym)))
    `(let ((,value ,val))
       ,(let iter ((list list))
          (if (pair? list)
              (let* ((item (car list))
                     (first (car item))
                     (result (cadr item))
                     (rest (cdr list)))
                 `(if (member ,value ',first)
                      ,result
                      ,(if (and (pair? rest)
                                (eq? (caar rest) 'else))
                           (cadar rest)
                           (if (not (null? rest))
                               (iter rest))))))))))


It's written in Scheme because that was my original implementation, I used
named let in Emacs you probably will need flet or create helper function
outside of macro. So I guess I will need to use that first implementation
only as example of recursive macro.

There is another example of recursive macros in book [Let Over Lambda][1] in
printed version on page 135. And there is also chapter in [On Lips][2] on page
139 where there is one problem that you may find (probably issue OP had) if
you expand with expansion that have `if` test inside, it will create infinite
loop, expansion need to be conditional so recursive check that stop the loop
need to be called at macro level, it can't be present in expansion.

This is example macro that will not work

(defmacro nthb (n lst)
  `(if (= ,n 0)
     (car ,lst)
     (nthb (- ,n 1) (cdr ,lst))))

here recursive guard is present in expansion and it will not compile becuase
it's infinite loop.


[1]: https://letoverlambda.com/index.cl/guest/chap5.html#sec_5
[2]: http://www.paulgraham.com/onlisptext.html

--
Jakub Jankiewicz, Web Developer
https://jcubic.pl/me

Attachment: pgpdCybLHpmCr.pgp
Description: Podpis cyfrowy OpenPGP


reply via email to

[Prev in Thread] Current Thread [Next in Thread]