This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

macro-function

4 posts · 1497 views

Hi,

I begin to study the macro-function in Lisp but there is something I 'don't understand in my push macro.
(setq place '(a b c))
(defmacro mypush (element place)
  (setq place '(cons 'element place)) )

(macroexpand-1 '(mypush a liste))
(cons 'element place) ;
t
It always returns me "element" as car of list, I understand why with the form to expand to, but I don't understand how to change that...

Can you help me a little ?

thanks a lot !

Last edited by nuntius on , edited 1 time in total. Reason: add code tag

Re: macro-function

Please use
 tags to maintain code formatting.

Macros in Lisp are an advanced topic, and your code sample indicates you do not yet understand the basics, in particular quoting and evaluation rules. A good book explaining Common Lisp from the basics, assuming some familiarity with programming in general, is [url=http://gigamonkeys.com/book/]Practical Common Lisp[/url]. There is also [url=http://www-2.cs.cmu.edu/~dst/LispBook/]Gentle Introduction to Symbolic Computation[/url] which is more theoretical and requires less programming knowledge.

Re: macro-function

When writing a macro, I find it is helpful to first write out the expansion.

So if you write (mypush item list) then what should the macroexpansion look like? Don't try to write the macro until you have an expansion to look at.

Re: macro-function

It should look like this:
(defmacro mypush (element place)
  `(setq ,place (cons ,element ,place)))
Alternatively, backticks and commas are syntactic sugar that are expanded to this:
(defmacro mypush (element place)
  (list 'setq place (list 'cons element place)))
Either of these two definitions will work, but the second might be more enlightening. Macros run their code; to generate code using a macro give it body-code that produces a s-expression. Backticks and commas make this quick and easy once you've gotten a feel for them -- but you can always build up lists directly as I've done in the second example.
Need an online wiki database? My Lisp startup http://www.formlis.com combines a wiki with forms and reports.