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?
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. (
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With