解析 Common Lisp 列表中的符号

发布于 2024-10-03 17:19:00 字数 302 浏览 6 评论 0原文

假设我有一个函数,

CL-USER> (defun trimmer (seq) "This trims seq and returns a list"
      (cdr 
         (butlast seq)))
TRIMMER
CL-USER> (trimmer '(1 2 3 VAR1 VAR2))
(2 3 VAR1)
CL-USER> 

请注意,由于 QUOTE,VAR1 和 VAR2 未解析。假设我想将符号 VAR1 和 VAR2 解析为其值 - 是否有标准函数可以执行此操作?

Suppose I have a function

CL-USER> (defun trimmer (seq) "This trims seq and returns a list"
      (cdr 
         (butlast seq)))
TRIMMER
CL-USER> (trimmer '(1 2 3 VAR1 VAR2))
(2 3 VAR1)
CL-USER> 

Notice how, due to QUOTE, VAR1 and VAR2 are not resolved. Suppose I want to resolve the symbols VAR1 and VAR2 to their values - is there a standard function to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愿与i 2024-10-10 17:19:00

不要使用 quote 创建包含变量的列表;使用 list 代替:(

CL-USER> (trimmer (list 1 2 3 var1 var2))
(2 3 value-of-var1)

其中 value-of-var1var1 的值)。

Quote 仅阻止对其参数进行评估。如果它的参数恰好是列表文字,则返回该值。但是,要创建不仅仅是文字的列表,请使用 list。您可以使用反引号语法,但在这种情况下这相当混乱。

Do not use quote to create a list with variables; use list instead:

CL-USER> (trimmer (list 1 2 3 var1 var2))
(2 3 value-of-var1)

(where value-of-var1 is the value of var1).

Quote only prevents evaluation of whatever its argument is. If its argument happens to be a list literal, then that is returned. However, to create lists that are not just literals, use list. You can use backquote syntax, but that is rather obfuscation in such a case.

自演自醉 2024-10-10 17:19:00

反引号是将值插入引用列表的常用方法:

> (setq var1 4 var2 5)
5
> `(1 2 3 ,var1 ,var2)
(1 2 3 4 5)

编辑添加:如果要处理列表以便将符号替换为其 symbol-value,那么你需要一个像这样的函数:

(defun interpolate-symbol-values (list)
  "Return a copy of LIST with symbols replaced by their symbol-value."
  (loop for x in list
        collect (if (symbolp x) (symbol-value x) x)))

> (interpolate-variables '(1 2 3 var1 var2))
(1 2 3 4 5)

然而,这似乎是一件奇怪的事情。您能详细谈谈您想要实现的目标吗?几乎可以肯定,有比这更好的方法。

Backquote is the usual way to interpolate values into a quoted list:

> (setq var1 4 var2 5)
5
> `(1 2 3 ,var1 ,var2)
(1 2 3 4 5)

Edited to add: if you want to process a list so that symbols are replaced with their symbol-value, then you need a function something like this:

(defun interpolate-symbol-values (list)
  "Return a copy of LIST with symbols replaced by their symbol-value."
  (loop for x in list
        collect (if (symbolp x) (symbol-value x) x)))

> (interpolate-variables '(1 2 3 var1 var2))
(1 2 3 4 5)

This seems like a strange thing to want to do, however. Can you say more about what you are trying to achieve? Almost certainly there's a better way to do it than this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文