JT93
JT93

Reputation: 511

Using Duplicate Values in a Clojure Set

I'm having a problem with sets in clojure where duplicate values are seemingly being removed from a set and it's causing me a real headache.

I have some cards.

(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}


    }
 )

These cards are then part of a set.

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

When I return this set I want to see the four nil's and three cards. Instead I get:

#{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}}

The reason I would like the duplicate values is situations in which I have two of the same card, or multiple nil values. I iterate through these values using a doseq loop that returns an out of bounds exception when duplicates are present.

Upvotes: 1

Views: 320

Answers (1)

Istvan
Istvan

Reputation: 8592

A Clojure set is by definition unique.

Returns a set of the distinct elements of coll.

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

If you need a non-unique set than you can use a vector or a list.

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

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

Upvotes: 4

Related Questions