Skip to content

Instantly share code, notes, and snippets.

@dfuenzalida
Created November 28, 2019 21:15
Show Gist options
  • Save dfuenzalida/f2cf44d6d2333365b8f53d55904c56f8 to your computer and use it in GitHub Desktop.
Save dfuenzalida/f2cf44d6d2333365b8f53d55904c56f8 to your computer and use it in GitHub Desktop.
Example of creating maps from a list of items
(ns mapsexample.core)
;; Version 1:
;; Given a list of items, loop through them, adding one at a time with `assoc`.
(defn build-map-1 [items]
(loop [n 0 ;; index to loop through the items
my-map (hash-map)] ;; or just {} for an empty hash-map
(if (>= n (count items))
my-map
(let [key (nth items n) ;; given an index, creates the key
val (str "item " key)] ;; create a value
(recur (inc n) ;; increase n for the next iteration
(assoc my-map key val)))))) ;; "update" my-map
;; (build-map-1 [3 4 5])
;; => {3 "item 3", 4 "item 4", 5 "item 5"}
;; Version 2:
;; Reducing small maps into a larger one
(defn key-value-for-item [item] ;; helper function, returns a small map for a given item
(hash-map item (str "Item " item)))
;; (key-value-for-item 120)
;; => {120 "Item 120"}
(defn build-map-2 [items]
(let [pairs (map key-value-for-item items)] ;; create pairs from the items
(reduce merge (hash-map) pairs))) ;; roll everything into a larger map
;; (build-map-2 [20 30 40 50])
;; => {20 "Item 20", 30 "Item 30", 40 "Item 40", 50 "Item 50"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment