如何使此宏按预期工作? [英] How to make this macro work as expected?

查看:92
本文介绍了如何使此宏按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 (defmacro switch [choices choice] '(do (choices choice)))
 (macroexpand-1 '(switch {1 (print 1) 2 (print 2)} (+ 1 1)))

 gives: (do (choices choice))


$ b b

只是为了学习宏,我想模拟开关情况,我会给一个字典有case作为键和代码执行作为值。

Just to learn macros, I wanted to emulate switch case where I will give a dictionary having case as keys and code to execute as values.

我想+ 1 1)得到求值为2,然后用作键来获取代码用do执行。

I wanted (+ 1 1) to get evaluated as 2 and then be used as key to get codde to execute with do.

但是,扩展宏给我们不解析的代码选择和选择。

However the expanded macro gives us code which doesn't resolve choices and choice both.

我试图取消选择和选择,不工作。
我在这里缺少什么?

I tried unquoting choice and choices, doesn't work. What am I missing here ?

推荐答案

取消定位可以工作,但是您需要从常规报价切换到语法-quote(backtick)for your quoting:

Unquoting does work, but you need to switch from the regular quote to syntax-quote (backtick) for your quoting:

(defmacro switch [choices choice]
  `(do (~choices ~choice)))

注意 do

请注意,使用此版本的 switch / code>调用将被评估,因为它们将简单地作为值表达式显示在开关的输出中的地图文字中。要有条件地打印,你必须使用一些条件构造( if case 他们)。我还要指出, choices 参数必须是文字映射,否则宏将无法获取键和值(在任何情况下

Note that with this version of switch, both print calls in your example will be evaluated, because they will simply appear as value expressions in a map literal in switch's output. To print conditionally, you'll have to use some conditional construct (if, case or something which expands to one of them). I'll also point out that the choices argument must be a literal map, or else the macro won't be able to get at the keys and values (and in any case the values would have been evaluated by the outer context).

这里是一个用上述内容写成的版本:

Here's a version written with the above in mind:

(defmacro switch [choices choice]
  `(case ~choice ~@(apply concat choices)))

来自REPL的示例:

user=> (switch {1 (print 1) 2 (print 2)} (+ 1 1))
2nil


$ b b

2 print 调用打印, nil 是返回值。)

(2 is printed by the print call, nil is the return value.)

这篇关于如何使此宏按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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