On Wed, Nov 19, 2008 at 4:16 PM, Mark Volkmann
<[EMAIL PROTECTED]> wrote:
>
> I'm reading an excellent article on functional programming at
> http://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);
> }

I don't believe Clojure supports this, no, though it has been brought
up before and I seem to recall somebody working on something. However,
this example can implemented using multimethods:

user=> (defmulti fib int)
#'user/fib
user=> (defmethod fib 0 [_] 1)
#<MultiFn [EMAIL PROTECTED]>
user=> (defmethod fib 1 [_] 1)
#<MultiFn [EMAIL PROTECTED]>
user=> (defmethod fib :default [n] (+ (fib (- n 2)) (fib (- n 1))))
#<MultiFn [EMAIL PROTECTED]>
user=> (map fib (range 10))
(1 1 2 3 5 8 13 21 34 55)

--~--~---------~--~----~------------~-------~--~----~
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