Help with macros

Started by cormullion, March 17, 2006, 12:37:01 AM

Previous topic - Next topic

cormullion

I'm trying to understand macros. I think I get the basic idea, from reading the manual, but - to be honest - I don't really see the point of doing things that way - rather than just use the language as it is. (I gather that they're also in old Lisp.)



So can someone point me to or supply a compelling use for macros, something that just can't be done any other way?



Thanks!

Lutz

#1
The first thing to mention is the fact that macros in newLISP are very different from macros in other LISPs. The page http://newlisp.org/index.cgi?page=Differences_to_Other_LISPs">http://newlisp.org/index.cgi?page=Diffe ... ther_LISPs">http://newlisp.org/index.cgi?page=Differences_to_Other_LISPs tells more about this.



In newLISP the difference between a function written with 'define' and 'define-macro' is that 'define' will evaluate all it's arguments, while 'define-macro' will not.



With 'define-macro' it is possible to make functions which behave and look like built-in fiunctions. I.e. the function (setq x y) does not evaluate the 'x' argument, but passes 'x' on directly as a symbol. The normal (set 'x y) doesn't work that way it evaluates bopth of it's arguments.



Another example is: (dolist (item mylist) .....). The expression (item mylist) is not evaluated but passed on into 'dolist' to deal with it. If not, we would have to quote doing (dolist '(item mylist) ...).



Macros are not used very often but when they are used they can be handy and important. The following example from init.lsp implements a 'defun' as found in Common LISP. Without 'define-macro' this would be impossible:



; usage example: (defun foo (x y z) ....)

(define-macro (defun _func-name _arguments)
      (set _func-name (append
        '(lambda )
         (list _arguments)
         (args))))


Without 'define-macro' you could only write a 'defun' where both the function name (i.e. foo) and the parameter list (i.e. (x y z)) would have to be quoted.



Lutz

cormullion

#2
OK - yes, I can see that it's a useful application!



But, these examples seem to be aimed at making old Lispers feel at home! ;-) Nothing wrong with that, of course. But if I'm happy with the current syntax of set and define, I don't feel that macros have any big advantages to offer me. Or do they?