【问题标题】:unexpected element in a list while concatenating new element连接新元素时列表中的意外元素
【发布时间】:2014-06-19 17:24:06
【问题描述】:

我编写了这个简单的buildPairs 函数,它应该接受一个列表和“某物”并返回一个对列表,其中每一对由列表中的一个元素和“某物”参数组成。

 4(defun buildPairs(aList rightChild)
 5  "returns a list of pairs"
 6  (setq ret (list (cons (car aList)
 7                        rightChild)))
 8  (setq newList (cdr aList))
 9  (while newList
10    (print (car newList))
11    (setq ret (append ret
12                      (list(cons (car newList)
13                                 rightChild))))
14
15    (setq newList (cdr newList)))
16
17  ret)
18
19(setq listA '("a1", "a2", "a3"))
20
21
22(length (buildPairs listA "foo"))

我希望22 行返回 3。 但由于某种原因,它返回 5,我不知道它为什么这样做。 它返回的列表是 (("a1" . "foo") (\, . "foo") ("a2" . "foo") (\, . "foo") ("a3" . "foo")) ,这很奇怪。

谁能解释一下我做错了什么?

【问题讨论】:

    标签: list elisp


    【解决方案1】:

    当我运行你的代码时,我得到了不同的结果:

    (("a1" . "foo") ((\, "a2") . "foo") ((\, "a3") . "foo"))
    

    这是因为listA 的值实际上是:

    ("a1" (\, "a2") (\, "a3"))
    

    你可能打算写这行不带逗号:

    (setq listA '("a1" "a2" "a3"))
    

    backquote syntax 中的逗号有特殊含义。由于它对以下列表元素应用了特殊含义,因此读者似乎将其呈现为函数调用,即包含“函数”名称和参数的列表。

    【讨论】:

    • 天啊!愚蠢的我!我在 Java 世界中生活太久了!(不知何故,我一直在想 args 需要用逗号分隔)谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-04-18
    • 2011-08-16
    • 1970-01-01
    • 2021-10-12
    • 2014-01-11
    • 2013-05-07
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多