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

2019-08-08 19:09发布

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?

1条回答
beautiful°
2楼-- · 2019-08-08 19:39

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))))
查看更多
登录 后发表回答