Running 4Clojure Problem 178 - The best hand I have is for converting map values ββfrom characters to numbers:
(fn [ch] (or ({\A 1} ch) ((zipmap "TJQK" (iterate inc 10)) ch) (- (int ch) (int \0))))
The zipmap expression is evaluated on every call, always creating {\K 13, \Q 12, \J 11, \T 10} .
How can we make the compiler evaluate it only once?
After long brain-beatings, I came up with
(defmacro constant [exp] (eval exp))
... ending the zipmap call zipmap this:
(constant (zipmap "TJQK" (iterate inc 10)))
I think this is equivalent
(eval '(zipmap "TJQK" (iterate inc 10)))
... but not up to eval without a quote:
(eval (zipmap "TJQK" (iterate inc 10)))
Corrections, comments and improvements are welcome.
source share