Skip to content

Instantly share code, notes, and snippets.

@MayDaniel
Forked from pepijndevos/project.clj
Created April 28, 2011 18:52
Show Gist options
  • Select an option

  • Save MayDaniel/947020 to your computer and use it in GitHub Desktop.

Select an option

Save MayDaniel/947020 to your computer and use it in GitHub Desktop.
seqex - a tiny pattern matcher in Clojure
(ns seqex.match)
(defn cps [funct cont]
(fn [[f & r :as s]]
(if (funct f)
(cont r)
false)))
(defn literal [l cont]
(cps (partial = l) cont))
(defn _ [cont]
(cps (constantly true) cont))
(defn other [funct _] funct)
(defmacro match
([form]
(if (seq? form)
`(~@form nil?)
`(~form nil?)))
([form & forms]
(if (seq? form)
`(~@form (match ~@forms))
`(~form (match ~@forms)))))
(defmacro coll [& forms]
`(cps #(and (coll? %)
((match ~@(drop-last forms)) %))
~(last forms)))
((match
(literal 1)
(coll (literal 3)
(other #(every? even? %)))
_
(literal 3))
[1 [3 4 2] 2 3])
; true
((literal 1 (literal 2 (literal 3 nil?))) [1 2 3])
; true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment