JT93
JT93

Reputation: 511

Extract value from list of hash-maps Clojure

I'm currently trying to get a value from a list of hash-maps.

  (def cards
  (hash-map
    :card1 {:name "Wisp" :damage 1 :health 1 :cost 0}
    :card2 {:name "Spider Tank" :damage 3 :health 4 :cost 3}
  )

I have a hash-map with my "cards".

(def deck1
      (list (get cards :card1) (get cards :card2) (get cards :card1))

And a deck which is a list of these cards. (I've shortened the two structures)

What I'm trying to do is search this deck structure for a card by passing it a card name. This card is kept as a var and passed elsewhere. I will then reconstruct the list without this card.

So, I'm trying to draw a specific card from anywhere in the deck.

Currently I'm just trying to get the card but I've hit a dead-end with the code.

(defn playCard [card]
(let [c first deck1 (get-in deck1 [card :name]))]
    (println "LOOK AT ME" c)))

Any help would be appreciated.

Upvotes: 2

Views: 629

Answers (1)

nha
nha

Reputation: 18005

Here is an example of how to retrieve your cards. I also refactored the declarations :

(def cards {:card1 {:health 1, :name "Wisp", :damage 1, :cost 0}, 
            :card2 {:health 4, :name "Spider Tank", :damage 3, :cost 3}})

(def deck [(:card1 cards)
           (:card2 cards)
           (:card1 cards)])

(defn find-first
     [f coll]
     (first (filter f coll)))

(find-first #(= (:name %) "Wisp") deck) ;; => {:health 1, :name "Wisp", :damage 1, :cost 0}

This is assuming you want to find a card by name (it doesn't make sense to look for a card you have already).

Upvotes: 2

Related Questions