如何编写将重复执行命令的宏? [英] How do I write a macro that will repeat a command?

查看:287
本文介绍了如何编写将重复执行命令的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个宏,使我可以在一个表达式中简化多个顶级变量的定义.

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

其想法是使它的工作方式与let的工作方式类似:

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))))

我尝试使用macroexpand,但它似乎根本没有扩展.

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?

推荐答案

dolist的返回值由其可选的第三个参数给出,因此您的宏返回默认值nil.

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

宏仅返回一种形式,因此,当您有多种内容(例如您的defparameters系列)时,需要将它们全部包装成某种形式并将其返回. progn在这里适用.例如:

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))))

这篇关于如何编写将重复执行命令的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆