On 19 Nov., 22:16, "Mark Volkmann" <[EMAIL PROTECTED]> wrote:
> I'm reading an excellent article on functional programming 
> athttp://www.defmacro.org/ramblings/fp.html. Toward the end there is a
> section on pattern matching. They give the following example which
> uses a fictional, Java-like syntax. Can Clojure do something like this
> where the fib function is overloaded using "patterns" instead of
> arity?
>
> int fib(0) { return 1; }
>
> int fib(1) { return 1; }
>
> int fib(int n) {
>     return fib(n - 2) + fib(n - 1);
>
> }

Pattern Matching is nothing but syntactic sugar.
It can be for some cases a way to express an algorithm with shorter
and more readable code.
In the case of fib this is in my opinion not the case.

Clojure offers Multimethods. They are not as general as PM, but
already
can do a lot of cases where PM would be used in other functional
programming languages.
One thing that Clojures Multimethods can’t do for example is something
like this:
(defmulti foo (fn [col] (count col)))  ; or:  (defmulti foo count)
(defmethod foo 3 [arg] (println "The" (class arg) arg "contains 3
elements"))
(defmethod foo 10 [arg] (println arg "contains 10 elements"))

And then:
user> (foo "yes")
The java.lang.String yes contains 3 elements
nil
user> (foo (range 10))
(0 1 2 3 4 5 6 7 8 9) contains 10 elements
nil

But now foo is determined to use as its dispatching function count.
If Clojure had pattern matching one could add another case which
would allow to say, additionally to the code above:

(add-another-defmulti foo first)
(defmethod foo "xyz" [x] (+ 1 2))
(defmethod foo \R [_] (range 5))

And then:
(foo ["xyz" 10 20 30 40 50 60]) ==> 3
(foo "Rich Hickey") ==> (0 1 2 3 4)

But one could express it in different ways in Clojure. Example:
user> (defn fu [col]
        (cond (= 3  (count col)) (println "The" (class col) col
"contains 3 elements")
              (= 10 (count col)) (println col "contains 10 elements")
              (= "xyz" (first col)) (+ 1 2)
              (= \R    (first col)) (range 5)))
#'user/fu
user> (fu "yes")
The java.lang.String yes contains 3 elements
nil
user> (fu (range 10))
(0 1 2 3 4 5 6 7 8 9) contains 10 elements
nil
user> (fu ["xyz" 10 20 30 40 50 60])
3
user> (fu "Rich Hickey")
(0 1 2 3 4)

This function fu is not really bad.
It needs to mention (count col) 2x while the multimethods
don’t have to do that, and it also needs to say (first col) 2x.
For more complex patterns PM really looks a bit nicer.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to