Clojure瞬态 - 结合!造成例外

jon*_*ohn 2 shuffle list clojure

这是我正在尝试运行的功能......

(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)))
Run Code Online (Sandbox Code Playgroud)

这导致了这个例外......

Exception in thread "main" java.lang.ClassCastException: clojure.lang.PersistentHashSet$TransientHashSet cannot be cast to clojure.lang.ITransientAssociative
Run Code Online (Sandbox Code Playgroud)

作为对clojure的新手,我也很感激对我上述方法的任何建设性批评.目标是获取List,并返回重新排序的列表.

Dan*_*ero 8

我假设您正在尝试实施Mongean shuffle.您的方法非常迫切,您应该尝试使用更实用的方法.

这是一个可能的实现,如果我们计算卡的最终顺序(根据维基百科公式),然后我们使用内置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)
Run Code Online (Sandbox Code Playgroud)