List Clojure瞬态-assoc!引起异常
这是我正在尝试运行的函数List Clojure瞬态-assoc!引起异常,list,clojure,shuffle,List,Clojure,Shuffle,这是我正在尝试运行的函数 (defn mongean [cards times] (let [_cards (transient cards)] (loop [i 0 c (get cards i) _count (count cards) _current (/ _count 2)] (assoc! _cards _current c) (if ((rem i 2) = 0) (def _newcur (- _current (inc i))
(defn mongean [cards times]
(let [_cards (transient cards)]
(loop [i 0 c (get cards i) _count (count cards) _current (/ _count 2)]
(assoc! _cards _current c)
(if ((rem i 2) = 0)
(def _newcur (- _current (inc i)))
(def _newcur (+ _current (inc i))))
(if (<= i _count)
(recur (inc i) (get cards i) _count _newcur )))
(persistent! _cards)))
作为clojure的新手,我也非常感谢对我上述方法的任何建设性批评。目标是获取一个列表,然后返回一个重新排序的列表。我假设您正在尝试实现洗牌。您的方法非常必要,您应该尝试使用更实用的方法 如果我们计算卡片的最终顺序(根据维基百科公式),然后使用内置的
replace
函数进行映射,这将是一个可能的实现:
(defn mongean [cards]
(let [num-cards (count cards)
final-order (concat (reverse (range 1 num-cards 2)) (range 0 num-cards 2))]
(replace cards final-order)))
user> (mongean [1 2 3 4 5 6 7 8])
(8 6 4 2 1 3 5 7)
你怎么称呼这个函数?看起来您正在传递一个集合,因此其瞬态版本也将是一个集合,因此不能与任何
assoc
函数一起使用,因为它们处理关联数据结构和向量:
user=> (assoc #{} :a 1)
ClassCastException clojure.lang.PersistentHashSet cannot be cast to clojure.lang.Associative clojure.lang.RT.assoc (RT.java:691)
user=> (assoc! (transient #{}) :a 1)
ClassCastException clojure.lang.PersistentHashSet$TransientHashSet cannot be cast to clojure.lang.ITransientAssociative clojure.core/assoc! (core.clj:2959)
; the following works as it uses maps and vectors
user=> (assoc {} :a 1)
{:a 1}
user=> (assoc! (transient {}) :a 1)
#<TransientArrayMap clojure.lang.PersistentArrayMap$TransientArrayMap@65cd1dff>
user=> (assoc [] 0 :a)
[:a]
如果您只是想洗牌:
(defn mongean [cards times] (shuffle cards))
重新排序的列表是什么意思?真聪明。。。clojure总是让我觉得自己像个白痴。。。谢谢您所说的“您的方法是非常必要的”是什么意思?对于那些不使用功能性风格的人,是否有来自OO经典背景的“黄金”资源?再次感谢。当我开始玩Clojure时,我错过了很多经典的命令
for
loop。没有它你怎么办。函数式编程的支柱之一是不使用变异状态。如果您使用transient
,您会立即说“我需要可变状态!”<如果确实需要性能提升,代码>瞬态应该保留给代码部分。关于什么资源,我只读了Clojure的书,但是搜索,所以有几个关于如何学习func编程的问题
(defn generate [coll] ; counts down from (count coll) to 0, change to
; implement your shuffling algorithm
(range (dec (count coll)) -1 -1))
(defn mongean [cards times]
(let [positions (generate cards) ; get the new positions
assemble (fn [dest [pos card]] ; assoc the card at the wanted position
(assoc dest pos card))]
(reduce assemble cards (map vector positions cards))))
(defn mongean [cards times] (shuffle cards))