更改向量列表中的值

时间:2016-12-07 14:37:15

标签: clojure

我知道如果我将团队定义为:

(def team ["A" "B" "C" "D"])

我可以通过

将值“B”更改为“E”
(assoc team 1 "E") > ["A" "E" "C" "D"]

如果我现在有:

(def teams '(["A" "B" "C"] ["D" "E" "F"] ["G" "H" "I"]))

如何将“B”更改为“1”,例如

我认为你可能不得不使用关联但这似乎不起作用或者我犯了一个错误。我试过了

(assoc-in teams [0 1] "1")

1 个答案:

答案 0 :(得分:4)

你几乎拥有它。当您应该使用向量时,您正在使用列表来执行您想要执行的操作:

(def teams [["A" "B" "C"] ["D" "E" "F"] ["G" "H" "I"]])

其原因是向量是关联结构(即,它是具有键/值对的结构)。它就像一个关联的地图,除了对于矢量,关键是矢量中的索引。将此与列表进行对比,该列表无法索引,必须迭代才能获得元素。因此,要使用 assoc -in,您需要使用关联结构,而列表则不会。

你得到的错误是:clojure.lang.PersistentList cannot be cast to clojure.lang.Associative,看一下来源就显示了这个:

IPersistentList给出:

public interface IPersistentList extends Sequential, IPersistentStack

Associative IPersistentVector对比:

public interface IPersistentVector extends Associative, Sequential, ...
相关问题