Building a Better Mapcro

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: