Building a Better Mapcro

By lispy

Larry Clapp recently responded to my post on making a “mapcar” type routine that works with macros. I managed to make an ugly hack that got the job done, but Larry shows us a much better approach. Instead of using mapcar to force eval to get something done, he uses a macro to expand out a list of expressions in a progn operation. Notice the trick of mapcar’ing a lambda expression that kicks out back-quoted list. That technique will surely be useful in other macros, but is not something I’ve seen highlighted in any tutorials, yet:

CL-USER>  (defmacro mapcro (macro &rest args)
           `(progn ,@(apply #'mapcar
                            (lambda (&rest args2)
                              `(,macro ,@args2))
                            args)))
MAPCRO
CL-USER>  (mapcro defparameter (a b c) (1 2 3))
C
CL-USER>  a
1
CL-USER>  b
2
CL-USER>  c
3
CL-USER>  (macroexpand-1 '(mapcro defparameter (x y z) (1 2 3)))
(PROGN (DEFPARAMETER X 1) (DEFPARAMETER Y 2) (DEFPARAMETER Z 3))
T

Leave a Reply