Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching functions in Clojure?

I have used erlang in the past and it has some really useful things like pattern matching functions or "function guards". Example from erlang docs is:

fact(N) when N>0 ->      N * fact(N-1);  fact(0) ->           1.     

But this could be expanded to a much more complex example where the form of parameter and values inside it are matched.

Is there anything similar in clojure?

like image 578
mikkom Avatar asked Dec 21 '11 22:12

mikkom


People also ask

What is core matching?

core. match - An optimized pattern matching library for Clojure[script] - is almost available for self-host clojuresript . It means that it can run in Planck and Klipse. There is a JIRA ticket for the port of core.match with a patch of mine - that makes core.match self-host compatible. (

What is pattern matching in Haskell with example?

We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.


2 Answers

There is ongoing work towards doing this with unification in the core.match ( https://github.com/clojure/core.match ) library.

Depending on exactly what you want to do, another common way is to use defmulti/defmethod to dispatch on arbitrary functions. See http://clojuredocs.org/clojure_core/clojure.core/defmulti (at the bottom of that page is the factorial example)

like image 62
gilesc Avatar answered Sep 24 '22 03:09

gilesc


I want to introduce defun, it's a macro to define functions with pattern matching just like erlang,it's based on core.match. The above fact function can be wrote into:

(use 'defun) (defun fact   ([0] 1)   ([(n :guard #(> % 0))]      (* n (fact (dec n))))) 

Another example, an accumulator from zero to positive number n:

(defun accum   ([0 ret] ret)   ([n ret] (recur (dec n) (+ n ret)))   ([n] (recur n 0))) 

More information please see https://github.com/killme2008/defun

like image 33
killme2008 Avatar answered Sep 24 '22 03:09

killme2008