Skip to content

Instantly share code, notes, and snippets.

@kapilreddy
Created October 21, 2013 15:04
Show Gist options
  • Save kapilreddy/7085400 to your computer and use it in GitHub Desktop.
Save kapilreddy/7085400 to your computer and use it in GitHub Desktop.
core.match macro with fns.
;; Match with guard function
(match [{:a 2} {:b 3}]
[{:a (_ :guard even?)} _] 1)
;; Match-with-fn example for same
(match [{:a 2} {:b 3}]
[{:a even?} _] 1)
(defmacro match-with-fn
[bindings & body]
(let [wrap-group (fn [m]
(if (map? m)
(apply hash-map (mapcat (fn [[k v]]
[k (if (eval `(or (fn? ~v)
(set? ~v)))
(list '_ :guard v)
v)])
m))
m))
body-new (mapcat (fn [[b val]]
[(if (keyword? b)
b
(mapv wrap-group b)) val])
(partition 2 body))]
`(ccm/match [~@bindings] ~@body-new)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment