| Paste number 63135: | naive case macro |
| Pasted by: | Chouser |
| When: | 3 years, 10 months ago |
| Share: | Tweet this! | http://paste.lisp.org/+1CPR |
| Channel: | #clojure |
| Paste contents: |
(defmacro case [val & pairs]
(let [val-sym (gensym 'val)]
`(let [~val-sym ~val]
(cond ~@(mapcat (fn [[k e]] `((= ~val-sym ~k) ~e))
(partition 2 pairs))))))
Annotations for this paste:
| Annotation number 1: | case with vectors and :else |
| Pasted by: | Chouser |
| When: | 3 years, 10 months ago |
| Share: | Tweet this! | http://paste.lisp.org/+1CPR/1 |
| Paste contents: |
(defmacro case
"Takes a keyform and a set of pattern/expr pairs. Patterns are
vectors whose values will be compared in turn against the value of
keyform. If any of the pattern values equals the keyform value, the
expr will be evaluated and returned. A pattern of :else always
matches. For convenience, non-vectors (except for :else) can be
used as a pattern when only a single value is needed for a given
expr."
[keyform & clauses]
(let [aks (gensym)]
(list `let [aks keyform]
(cons `cond
(mapcat (fn [[k e]]
[(if (= k :else)
k
(cons `or (map #(list `= aks %)
(if (vector? k) k [k]))))
e])
(partition 2 clauses))))))