Pattern matching support in clojure
Lisp is loved and hated because of its syntax, but the fact is that the homogenous treatement of data and code in the language has allowed Lisp to evolve and incorporate into the language those features considered necessary by their users without modifications in the core language.
Clojure, as any other incarnation of Lisp, has inherited this extensibility capacities and takes advantage of it in different ways.
This post is introduces a library for adding pattern matching support in the Clojure in about 100 lines of code.
You can download the library from my github repository: http://github.com/antoniogarrote/clj-tuples
The library adds two constructs 'match' and 'case' to test patterns against values, and execute clojure forms associated to a succesful match.
These are some examples of how to use the library, any user of Haskell or Erlang will recognize the syntax inmediately:
user>(tuples/match true true nil) nil user>(tuples/match true false nil) matching exception user>(tuples/match a true a) true user>(tuples/match a true (not a)) false user>(def v '(1 2 (3 4) 5)) #'user/v user>(tuples/match (z u (s1 s2) t) v (println s1)) 3 user>;you can use _ if you are not interested in a part of the value nil user>(tuples/match (_ _ s _) v s) (3 4) user>(def *extracted* (tuples/match (z u (s1 s2) t) (1 2 (3 4) 5) s2) s2)) #'user/*extracted* user>*extracted* 4 user>(tuples/match (3 u (s1 s2) t) (1 2 (3 4) 5) (println s2)) matching exception user>(def vu '(2 2)) #'user/vu user> (tuples/case (vu 2) (z 1) (println (str "a " z)) (z 2) (println (str "b " z)) t :error) b (2 2) user>(tuples/case (vu 3) (z 1) (println (str "a " z)) (z 2) (println (str "b " z)) t :error) :error
The library is not meant to be complete, it only works with lists for doing deep matching but is a good example of how Clojure can be extended.
Hope someone finds it useful!

jneira dijo
beautiful library, im going to watch it closely ;-) ..
29 Septiembre 2009 | 03:09 PM