首页 > 解决方案 > 如何在 Lisp 的宏中修复“X 不是数字”

问题描述

我开始学习 lisps,目前正在为学校开发宏。我在一个名为 decrement.txt 的 txt 文件中创建了一个名为“-=”的简单宏

(defmacro -= (numericValue decrementValue)
   (list 'setf numericValue (- numericValue decrementValue))
)

所以传递的参数是 numericValue(将被递减的值)和 decrementValue(numericValue 将被递减的数量)

当我在 CLISP(即 GNU CLISP 2.49)中运行代码时,我运行它如下...

[1]> (load "decrement.txt" :echo T :print T)

;; Loading file pECLisp.txt ...
(defmacro -= (numericValue decrementValue)
    (list `setf numericValue (- numericValue decrementValue))
)
-=


;;
;; Loaded file pECLisp.txt
T
[2]> (setf x 5 y 10)
10
[3]> (-= x 1)
*** - -: X is not a number
The following restarts are available:
USE-VALUE      :R1      Input a value to be used instead.
ABORT          :R2      Abort debug loop
ABORT          :R3      Abort debug loop
ABORT          :R4      Abort main loop

“X不是数字”是什么意思,这与宏如何不知道变量的实际值有关吗?因为当我输入USE-VALUE并输入 5(X 应该是这个值)时,它运行得非常好,即使我(print x)将 x 显示为 4,因为它在函数中被递减了。所以值会发生应有的变化,但是当我最初运行该“-=”函数时,它会给出该错误,我该如何解决?

标签: common-lispclisplisp-macros

解决方案


辛苦了,您只在宏中缺少对参数的评估。如果你使用 `(斜引号),你可以写成:

(defmacro -= (numericValue decrementValue)
   `(setf ,numericValue (- ,numericValue ,decrementValue))
)

现在你可以这样做:

(-= x 1)  => 4
x  => 4

推荐阅读