Created
February 7, 2012 15:48
-
-
Save blacktaxi/1760333 to your computer and use it in GitHub Desktop.
Macros for defining constants in Clojure
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
(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