【问题标题】:How to change content of quoted value in Guile如何在 Guile 中更改引用值的内容
【发布时间】:2020-07-03 06:26:49
【问题描述】:

我有一个计算结果为 (quote ("all")) 的符号。我想将“测试”附加到列表的末尾,并获得 (quote ("all" "tests")) 但我没有找到如何:

(define make-flags ''("all"))
(append make-flags '("tests")) ; Resolves to (quote ("all") "tests")

我想我必须通过两次评估 make-flags 并重新引用它来删除引用,但我没有找到方法。

【问题讨论】:

  • 请注意,''("all") 的计算结果为 (quote (quote ("all"))),而不是 (quote ("all")),因为开头有双单引号。这是你真正需要的吗?
  • 是的,就是这样定义的。我的意思是“一旦评估,它会解析为(quote ("all")),但我是新手,我可能错了。
  • 请注意 (quote ("all")) 只是 '("all"),但您正在编写 ''("all")。额外的报价使一切变得不同!但无论如何,我不确定你的用例是什么。我的回答解决了你原来的问题;)
  • @ÓscarLópez 我不太同意你们的 cmets 关于这里的引用和评估。 ''("all") 确实评估为'("all"),就像'x 评估为x'3 评估为3。我们必须引用这些值来谈论它们,但这并不意味着引用是它们实际值的一部分
  • @amalloy 方案将(quote whatever) 评估为whatever'whatever(quote whatever) 的缩写,所以 ''x 将评估 (quote (quote x)) 成为一个愚蠢的列表 (quote x) 但某些 REPL 可能显示为 'x。不犯错误。该值是一个包含两个符号的列表,符号quote 没有比x 更特别的地方。作为数据,它们对语言同样无趣。

标签: scheme guile


【解决方案1】:

是的,您需要先删除引号。试试这个:

(define make-flags ''("all"))
`'(,(append (cadr make-flags) '("tests")))
=> ''("all" "tests")

之所以有效,是因为make-flags 只是这种形式的列表:(quote (quote ("all"))),我们可以使用carcdr 以通常的方式导航它。

【讨论】:

  • 在我的解释器上,它显示("all" "tests"),而我想要(quote ("all tests"))。如果可能的话,有没有办法在附加评估之后重新引用它?
  • 我认为您误解了解释器显示结果的方式。 ("all" "tests") 正是 Guile 显示 (quote ("all" "tests")) 的方式。所以引用 is 已经存在,只是没有显示。这可以解释一切;)
  • 无论如何:如果你真的,真的想要那个额外的引号,这样做(注意开头的反​​引号!):`'(,(append (cadr make-flags) '("tests ")))
  • "("all" "tests") 正是 Guile 显示 (quote ("all" "tests")) 的方式" 是的,但是当我输入 make-flags 时,我得到 (quote ("all")),所以在原始值上有第二个引号。但是感谢最后的 sn-p。
【解决方案2】:

你评估''("all") 的第二个你得到列表(quote ("all")),它根本不是引用列表。这是一个 to 元素列表,符号 quote 和列表 ("all")。如果您想将一个元素添加到第二个元素,您可以通过重新创建外部列表并将第二个列表替换为带有添加元素的新列表:

(define (add-second-element ele lst)
  `(,(car lst) (,@(cadr lst) ,ele) ,@(cddr lst)))
    
(add-second-element 'goofy '((donald dolly) (mickey) (chip dale)))
; ==> (donald (mickey goofy) (chip dale))

(add-second-element "tests" ''("all"))
; ==> (quote ("all" "tests")) 

如果您对 quasiquote 不太熟悉,也可以不用,因为 quasiquote 只是 consappend 的精美语法糖:

(define (add-second-element-2 ele lst)
  (cons (car lst) (cons (append (cadr lst) (list ele)) (cddr lst))))

(add-second-element-2 'goofy '((donald dolly) (mickey) (chip dale)))
; ==> (donald (mickey goofy) (chip dale))

当然,如果第一个元素始终是 quote 并且只有两个元素,那么这两个版本都可以轻松简化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2015-05-18
    • 2021-08-02
    相关资源
    最近更新 更多