我遇到了一个问题,即我的向量突然变得不可变。我想知道是否有办法创建给定集合的新鲜的,不变的向量副本。
Clojuredocs建议使用“克隆”,但这给我一个错误,指出没有这种方法。
(defn stripSame [word wordList]
(def setVec (into #{} wordList))
(def wordSet word)
(def wordVec (into #{} [wordSet]))
(def diffSet (set/difference setVec wordVec))
(def diffVec (into [] diffSet))
diffVec)
(defn findInsOuts [word passList]
(def wordList (stripSame word passList))
(println word wordList)
(def endLetter (subs word (dec (count word))))
(def startLetter (subs word 0 1))
(println startLetter endLetter)
(def outs (filter (partial starts endLetter) wordList))
(def ins (filter (partial ends startLetter) wordList))
;(println ins outs)
(def indexes [ (count ins) (count outs)])
indexes)
(defn findAll [passList]
(def wordList (into [] passList) ))
(println wordList)
(loop [n 0 indexList []]
(println "In here" (get wordList n) wordList)
(if (< n (count wordList))
(do
(def testList wordList)
(def indexes (findInsOuts (get wordList n) testList))
(println (get wordList n) indexes)
(recur (inc n) (conj indexList [(get wordList n) indexes]))))))
passList是这样的单词列表(大声笑),然后将其转换为向量。
因此,基本上,findAll调用findInsOuts,它遍历列表中的每个单词,并查看有多少个其他单词以其最后一个字母开头,但首先从向量中删除搜索单词,然后执行某些功能以防止重复。问题在于该向量实际上是可变的,因此在findAll 中向量的副本也将永久删除该值。
当我尝试创建一个新的向量然后对该向量执行操作时,仍然会发生相同的情况,这意味着它们被别名/共享了相同的内存位置。
我该如何创建实际上不可变的新载体来使用?
感谢您的帮助
答案 0 :(得分:3)
恐怕您的代码充满误解。首先,请勿在{{1}}中使用def
。请改用defn
。这会将您的第一个功能变成...
let
例如,
(defn stripSame [word wordList]
(let [setVec (into #{} wordList)
wordSet word
wordVec (into #{} [wordSet])
diffSet (clojure.set/difference setVec wordVec)
diffVec (into [] diffSet)]
diffVec))
功能可以简化为...
=> (stripSame 2 [1 2 :buckle-my-shoe])
[1 :buckle-my-shoe]
...或使用线程宏来...
(defn stripSame [word wordList]
(vec (disj (set wordList) word)))
我不认为函数会像您想象的那样执行操作,因为它并不总是保留向量中元素的顺序。
如果我是你,我将按照this page上的一些社区教程进行工作。这里也提到了几本好书。一旦掌握了该语言的习惯用法,您就会发现您尝试做的事情更加清晰和容易。