Skip to content

Instantly share code, notes, and snippets.

@divs1210
Last active February 5, 2018 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divs1210/299bfcd4d3e90e84f561e56af759d782 to your computer and use it in GitHub Desktop.
Save divs1210/299bfcd4d3e90e84f561e56af759d782 to your computer and use it in GitHub Desktop.
Immutable hashmap implemented as a Clojure macro
(ns hmap)
(defmacro hmap [& kvs]
"Returns an immutable hashmap.
Keys must be compile-time constants."
(if (even? (count kvs))
(let [tups (partition 2 kvs)
keys (mapv first tups)
kvs+ (concat kvs [::keys keys])]
`(fn [k#]
(case k# ~@kvs+)))
(throw (Exception. "hmap takes an EVEN number of args"))))
(comment
(def m (hmap :a 1 :b 2))
;; => #'hmap/m
(m ::keys)
;; => [:a :b]
(m :a)
;; => 1
(m :c)
;; => IllegalArgumentException No matching clause: :c
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment