Reputation: 51
I am confused as to what &rest
does in common lisp.
This could be an example to represent what I mean :
(defmacro switch (value &rest pairs)
....
)
What exactly does the &rest and pairs mean?
Upvotes: 0
Views: 247
Reputation: 27414
The last parameter in a function (or macro) definition can be preceded by &rest
. In this case, when the function (or the macro) is called, all the arguments not bound to the previous parameters are collected into a list which is bound to that last parameter. This is a way of providing an unspecified number of arguments to a function or a macro.
For instance:
CL-USER> (defun f (a &rest b)
(list a (mapcar #'1+ b)))
F
CL-USER> (f 1 2 3 4 5)
(1 (3 4 5 6))
CL-USER> (f 1)
(1 NIL)
CL-USER> (f 1 2 3)
(1 (3 4))
CL-USER> (defmacro m (f g &rest pairs)
(let ((operations (mapcar (lambda (pair) (list g (first pair) (second pair))) pairs)))
`(,f (list ,@operations))))
M
CL-USER> (macroexpand-1 '(m print + (1 2) (3 4) (5 6)))
(PRINT (LIST (+ 1 2) (+ 3 4) (+ 5 6)))
T
CL-USER> (m print + (1 2) (3 4) (5 6))
(3 7 11)
Note that, if the are no remaining arguments, the list passed to the last parameter is empty.
Upvotes: 6