Skip to content

Instantly share code, notes, and snippets.

@pthatcher
Created February 25, 2010 01:55
Show Gist options
  • Save pthatcher/314129 to your computer and use it in GitHub Desktop.
Save pthatcher/314129 to your computer and use it in GitHub Desktop.
;; clojure's (case ...) macro doesn't allow *constant-vars* in the test cases, which I find really, really annoying.
;; So, I wrote a (case-eval ...) macro that wraps (case ...) and evals the test cases. If you like the (case ...) macro
;; and want to use *globals*, here's your fix. It works pretty much transparently.
(defn count-from [start]
(iterate inc start))
; like python
(defn zip [& lists]
(apply map vector lists))
; like python
(defn enumerate [vals]
(zip (count-from 0) vals))
(defn map-when-index [p? f vals]
(for [[index val] (enumerate vals)]
(if (p? index)
(f val)
val)))
(defn eval-all [val]
(if (seq? val)
(map eval val)
(eval val)))
(defmacro case-eval [e & clauses]
"Just like case, but it evals the test case so that you can use
*constants* in the tests."
`(case ~e ~@(map-when-index even? eval-all clauses)))
(def *abc* "ABC")
(case-eval "ABC"
"ABC"
:abc)
;; this doesn't work
;(case "ABC"
; *abc*
; :abc)
;but this does
(case-eval "ABC"
*abc*
:abc)
;and so does this
(case-eval "ABC"
(*abc* "xyz")
:abc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment