Paste number 63135: naive case macro

Index of paste annotations: 1

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:
Raw Source | XML | Display As
(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:
Raw Source | Display As
(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))))))

Colorize as:
Show Line Numbers
Index of paste annotations: 1

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.