2005/5/10

     
 

ACDK Lisp Macros

artefaktur

Macros give Lisp the possibility to redesign its own language


Content of this chapter:

   Backquote and comma operator
   Define a macro with defmacro



 Backquote and comma operator


An expression can be quoted to protect the quoted expression for evaluation:

;; Quote an atom:
'a
;; Quote a list
'(a b c)
; -> (a b c)

An expression can also be backquoted.


;; Quote an atom:
`a
;; Quote a list
`(a b c) 
; -> (a b c)

The both expression are qually as long no comma or comma-at operator are defined:
With the comma operator the next token will 'unquoted' and will be evaled:


(setf b 1)
(setf l '(d e f))
`(a ,b ,l c)
; -> (a 1 (d e f) c)

The difference between the comma an the comma-at operator is that the the comma-at operator will replace the resulting list elements not the list.


(setf l '(d e f))
`(a ,l c)
; -> (a  (d e f) c)
`(a ,@l c)
; -> (a  d e f c)

!

ACDK Lisp doesn't support multiple backquotes and comma operators.

 Define a macro with defmacro



(defmacro nil! (nilatt_a)
  (setf nilatt_a nil)
)

(setf a 32)
(nil! a)

Macros will be evaluated by parse time, not at runtime.
The resulting atom or list will be replaces at place where the macro was called: The code will will be 'patched'.
After parsing the code above:

(setf a 32)
(setf a nil)

The power of macros will be evolved in corporatation with the backquotes an the comma operators.


(defmacro doaddition (&rest doaddition_args)
  `(+ ,@doaddition_args) ; replaces the argument list directly
)
(setf a 3)
(doaddition 1 a 4)

Will expand to:

(setf a 3)
(+ 1 a 4)

Please refer to online LISP manuals (google Lisp defmacro) for more information.