Pattern matching functions in Clojure?

mikkom picture mikkom · Dec 21, 2011 · Viewed 18.9k times · Source

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?

Answer

gilesc picture gilesc · Dec 21, 2011

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)