Last active
February 5, 2018 08:56
-
-
Save divs1210/299bfcd4d3e90e84f561e56af759d782 to your computer and use it in GitHub Desktop.
Immutable hashmap implemented as a Clojure macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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