Page 1 of 1
macro-function
Posted: Sun Oct 31, 2010 11:45 am
by natilus
Hi,
I begin to study the macro-function in Lisp but there is something I 'don't understand in my push macro.
Code: Select all
(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 !
Re: macro-function
Posted: Sun Oct 31, 2010 12:13 pm
by ramarren
Please use
Code: Select all
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
Posted: Sun Oct 31, 2010 2:13 pm
by nuntius
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
Posted: Fri Nov 05, 2010 10:07 am
by Warren Wilkinson
It should look like this:
Code: Select all
(defmacro mypush (element place)
`(setq ,place (cons ,element ,place)))
Alternatively, backticks and commas are syntactic sugar that are expanded to this:
Code: Select all
(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.