简体   繁体   中英

How do I write a macro that will repeat a command?

I'm trying to write a macro that will let me streamline the definition of multiple top-level variables in one single expression.

The idea was to make it work similar to how let works:

(defparameters ((*foo* 42)
                (*bar* 31)
                (*baz* 99)))

I tried using the following, but it doesn't seem to do anything.

(defmacro defparameters (exprs)
  (dolist (expr exprs)
    (let ((name (car  expr))
          (exp  (cadr expr)))
      `(defparameter ,name ,exp))))

I've tried using macroexpand but it doesn't seem to expand at all.

What am I doing wrong? and how can I fix it?

The return value of a dolist is given by its optional third argument, so your macro returns the default of nil .

Macros only return one form, so when you have multiple things, such as your series of defparameters , you need to wrap them all in some form and return that. progn will be suitable here. For Example:

(defmacro defparameters (exprs)
  `(progn ,@(loop for (name exp) in exprs
                  collect `(defparameter ,name ,exp))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM