lisp - Lisp Case 语句中的动态变量

标签 lisp common-lisp

我用 common lisp 写了这段代码(忽略 ...,因为将那部分粘贴在这里毫无意义)。

(case turn 
   (*red-player* ...)
   (*black-player* ...)
   (otherwise ...))

red-playerblack-player 是使用 defvar 语句定义的变量,目的是“模拟”C 中的#define 语句。

(defvar *red-player* 'r)
(defvar *black-player* 'b)

你可以想象,当变量 turn收到 *red-player*的值 ('r) 或 *black-player*的值 ('b),case 语句不能正常工作,因为它期望 turn 包含 *red-player*作为文字,而不是变量的内容 *red-player* .

我知道我可以使用 cond 或 if + equal 语句轻松解决这个问题,因为变量的内容是在那里计算的,但我很好奇。也许有一种方法可以在 Lisp 中创建类似于 C 的宏,或者有某种特殊的 case 语句允许使用变量而不是仅使用文字。

提前致谢!

最佳答案

您可以使用读取时求值将表达式的值输入到您的表单中

CL-USER 18 > (defvar *foo* 'a)
*FOO*

CL-USER 19 > (defvar *bar* 'b)
*BAR*

CL-USER 20 > '(case some-var (#.*foo* 1) (#.*bar* 2))
(CASE SOME-VAR (A 1) (B 2))

请注意,读取时评估不一定​​是改进代码维护和安全性的最佳想法。

另请注意,在 Lisp 中不需要为某些内部值提供具有描述性名称的变量的想法:

dashedline = 4
drawLine(4,4,100,100,dashedline)

会在 Lisp 中

(draw-line 4 4 100 100 :dashed-line)

在 Lisp 中,可以传递描述性命名的符号。使用整数值或类似值的 API 仅在通常用 C 编写的外部软件的 API 中需要。

关于lisp - Lisp Case 语句中的动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479471/

相关文章:

clojure - 无法在 Clojure 中定义类?

lambda - 列表应该是一个 lambda 表达式

lisp - Common Lisp程序错误

lisp - 在 Common LISP 中更改中流字节宽度

lisp - 普通口齿不清 : How to quote parenthese in SBCL

lisp - 在 lisp 中创建将从列表中找到值的 assoc 函数

Lisp函数解释

pointers - 通用 Lisp CFFI : pointer to the pointer

common-lisp - Lisp 中的词法绑定(bind)

lisp - 在 Common Lisp 的列表中查找嵌套最多的列表