Discussion of Common Lisp
-
natilus
- Posts: 1
- Joined: Sun Oct 31, 2010 11:27 am
Post
by natilus » Sun Oct 31, 2010 11:45 am
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 !
Last edited by
nuntius on Sun Oct 31, 2010 2:08 pm, edited 1 time in total.
Reason: add code tag
-
ramarren
- Posts: 613
- Joined: Sun Jun 29, 2008 4:02 am
- Location: Warsaw, Poland
-
Contact:
Post
by ramarren » Sun Oct 31, 2010 12:13 pm
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.
-
nuntius
- Posts: 538
- Joined: Sat Aug 09, 2008 10:44 am
- Location: Newton, MA
Post
by nuntius » Sun Oct 31, 2010 2:13 pm
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.
-
Warren Wilkinson
- Posts: 117
- Joined: Tue Aug 10, 2010 11:24 pm
- Location: Calgary, Alberta
-
Contact:
Post
by Warren Wilkinson » Fri Nov 05, 2010 10:07 am
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.