Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Macros for defining constants in Clojure
(defmacro defconst [const-name const-val]
`(def
~(with-meta const-name
(assoc (meta const-name) :const true))
~const-val))
(defmacro defconsts [bindings]
`(do
~@(map (fn [[const-name const-val]]
`(defconst ~const-name ~const-val))
(partition 2 bindings))))
;;
; user=> (defconst pi 3.14)
; #'user/pi
; user=> (meta (var pi))
; {:ns #<Namespace user>, :name pi, :const true, :line 15, :file "NO_SOURCE_PATH"}
; user=> (time (dotimes [_ 1e10] (* pi pi)))
; "Elapsed time: 3025.789399 msecs"
; nil
; user=> (time (dotimes [_ 1e10] (* 3.14 3.14)))
; "Elapsed time: 3014.558959 msecs"
; nil
; user=> (defconsts [e 2.7
; e2 (* e 2)])
; #'user/e2
; user=> (time (dotimes [_ 1e10] (* e e2)))
; "Elapsed time: 3017.421303 msecs"
; nil
; user=> (meta (var e))
; {:ns #<Namespace user>, :name e, :const true, :line 20, :file "NO_SOURCE_PATH"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment