Skip to main content
edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

clojure/clojurescript: elegant way to generate Generate a deck of cards? in Clojure / Clojurescript

Post Migrated Here from stackoverflow.com (revisions)
Source Link
mye
  • 43
  • 2

clojure/clojurescript: elegant way to generate a deck of cards?

I would like to generate a deck of cards:

{:card-id 1 :suit :spade :rank 1}
{:card-id 2 :suit :spade :rank 2}
...
{:card-id 52 :suit :club :rank 13}

And here is my attempt:

(defn new-deck []
  (let [cards (flatten
                 (for [suit [:spade :heart :diamond :club]]
                    (for [rank [1 2 3 4 5 6 7 8 9 10 11 12 13]]
                      {:suit suit :rank rank} )))]
     (map-indexed (fn [idx itm] {:card-id (inc idx)
                                 :suit    (:suit itm)
                                 :rank    (:rank itm)})
                  cards)))

The code works but I think it is awkward. Especially the part where I use map-indexed function to add :card-id to each card.

Any suggestions to improve the code snippet?