宏扩展:引用身体形式与否? [英] macro expansion: to quote the body forms or not?

查看:78
本文介绍了宏扩展:引用身体形式与否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难确切了解宏扩展的工作原理。 elisp解释器处理这两个代码片段有什么区别?

I'm having a hard time understanding exactly how macro expansion works. What is the difference in how the elisp interpreter handles these two snippets of code?

(defmacro foo (arg)
  (message "arg is: %s" arg))
(foo "bar")

和:

(defmacro foo (arg)
  `(message "arg is: %s" ,arg))
(foo "bar")


推荐答案

您的示例可能会令人困惑,因为



You example may be confusing because


  1. 消息显示一条消息并返回

  2. 字符串(如 bar)是自评估的。

  1. message both displays a message and returns it.
  2. strings (like "bar") are self-evaluating.



教学示例



Instructive Example

(defconst zzz 123)
(defmacro zzz1 (arg)
  `(insert (format "arg is: %s" ,arg)))
(defmacro zzz2 (arg)
  (insert (format "arg is: %s" arg)))

在3种形式中的每一种之后使用 Cx Ce 评估以上代码。

Evaluate the code above using C-x C-e after each of the 3 forms.

现在评估以下内容:

解释器...


  1. 调用 zzz1
  2. 的宏函数
  3. 宏函数返回(插入(格式为 arg is:%s zzz))

  4. 解释器评估该表单,并插入 arg是:123 进入当前缓冲区,并返回 nil (在底部的回显区域中看到)

  1. calls the macro function of zzz1
  2. the macro function returns the form (insert (format "arg is: %s" zzz))
  3. the interpreter evaluates the form, and inserts "arg is: 123" into the current buffer, and returns nil (seen in the echo area at the bottom)



第二版本:(zzz2 zzz)



解释器...

Second version: (zzz2 zzz)

The interpreter...


  1. 调用 zzz2
  2. 宏函数在当前缓冲区中插入 arg is:zzz 并返回 nil

  3. 解释器将 nil 评估为 nil (在回显中看到

  1. calls the macro function of zzz2
  2. the macro function inserts "arg is: zzz" in the current buffer and returns nil
  3. the interpreter evaluates nil to nil (seen in the echo are at the bottom)



最重要的



最重要的 -away是宏只是对代码进行操作的函数在编译器的解释器启动之前。

The bottom line

The most important "take-away" here is that macros are just functions which operate on code before the interpreter (of compiler) kicks in.

这些函数的参数未计算(即,在两个 zzz1 中)和 zzz2 arg zzz ,而不是 123 )。

These functions take their arguments unevaluated (i.e., in both zzz1 and zzz2, arg is zzz, not 123).

对它们的评估与其他任何lisp函数一样(例如,它们的主体中可以具有宏形式;主体被隐式 progn ;& c)。

They are evaluated like any other lisp function (e.g., they can have macro forms in their bodies; the body is wrapped in an implicit progn; &c).

它们的返回值由解释器而不是原始格式评估。

Their return value is evaluated by the interpreter instead of the original form.

这篇关于宏扩展:引用身体形式与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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