代码之家  ›  专栏  ›  技术社区  ›  JT93

在Clojure集中使用重复值

  •  1
  • JT93  · 技术社区  · 9 年前

    我对clojure中的集合有一个问题,重复的值似乎被从集合中删除,这让我非常头疼。

    我有一些卡片。

    (def cards
      {
        :card1 {:name "Wisp"              :type "Monster"     :damage 1   :health 1   :cost 0 :ability 0}
        :card2 {:name "Spider Tank"       :type "Monster"     :damage 3   :health 4   :cost 3 :ability 0}
        :card3 {:name "Boulder Fist Ogre" :type "Monster"     :damage 6   :health 7   :cost 6 :ability 0}
        :card4 {:name "Bloodfen Raptor"   :type "Monster"     :damage 3   :health 2   :cost 2 :ability 0}
        :card5 {:name "Chillwind Yeti"    :type "Monster"     :damage 4   :health 5   :cost 4 :ability 0}
        :card6 {:name "Magma Rager"       :type "Monster"     :damage 5   :health 1   :cost 3 :ability 0}
        :card7 {:name "War Golem"         :type "Monster"     :damage 7   :health 7   :cost 7 :ability 0}
        :card8 {:name "Oasis Snapjaw"     :type "Monster"     :damage 2   :health 7   :cost 4 :ability 0}
        :card9 {:name "River Crocolisk"   :type "Monster"     :damage 2   :health 3   :cost 2 :ability 0}
        :card10 {:name "Murloc Raider"    :type "Monster"     :damage 2   :health 1   :cost 1 :ability 0}
        :card11 {:name "Northshire Cleric":type "Monster"     :damage 1   :health 3   :cost 1 :ability 2}
    
    
        }
     )
    

    这些卡片是一套卡片的一部分。

     (def board1 (set (map cards '(:card3 :card4 :card11 nil nil nil nil))))
    

    当我回这一盘时,我想看到四张0和三张牌。相反,我得到:

    #{nil {:ability 0, :name "Bloodfen Raptor", :type "Monster", :damage 3, :health 2, :cost 2} {:ability 0, :name "Boulder Fist Ogre", :type "Monster", :damage 6, :health 7, :cost 6} {:ability 2, :name "Northshire Cleric", :type "Monster", :damage 1, :health 3, :cost 1}}
    

    我想要重复值的原因是我有两张相同的卡,或者有多个零值。我使用doseq循环遍历这些值,当存在重复项时,该循环返回越界异常。

    1 回复  |  直到 9 年前
        1
  •  4
  •   Istvan    9 年前

    根据定义,Clojure集合是唯一的。

    返回coll的一组不同元素。

    https://clojuredocs.org/clojure.core/set

    如果您需要一个非唯一的集合,那么可以使用向量或列表。

    https://clojuredocs.org/clojure.core/vec

    https://clojuredocs.org/clojure.core/list