Hey all,

So, for a random project, I found myself using a single protocol
extended to a bunch of record types. I did this using the support
in `defrecord` itself, but what I dislike about it is that the
definitions for each method of the protocol are spread out amongst
multiple sections of code.

What I'd really like to do would be to define an implementation for
many types within a single definition. Conceptually, this is the
same thing you might do in OCaml or other staticly typed languages:

let bar x = match x with
   | String y -> ...
   | Character y -> ...

So, I came up with this (below), only it doesn't work. I haven't dug deep
yet to figure out why exactly, or if this could even technically be done
without manipulating something in core. (I'm going to assume for now
that I missed something simple, and it could be fixed trivially.)

(defprotocol Foo
  (bar [_] "do bar")
  (baz [_] "do baz"))

(defmacro defp [proto name arglist & bodies]
  (let [pairs (partition 2 bodies)
        protocol (resolve proto)
        namekw (keyword name)
        impls (reduce (fn [accum [t body]]
                        (let [tm (assoc
                                     (get accum t {})
                                   namekw `(fn ~arglist ~body))]
                          (assoc accum t tm)))
                      (get :impls protocol {})
                      pairs)]
    `(def ~proto (assoc (var-get ~protocol) :impls ~impls))))

(defp Foo bar [x]
  String (concat x x)
  Character (list x x))

(defp Foo baz [x]
  String (rest (seq x))
  Character nil)


So, is there a technical reason why this is a bad idea, other than
"the interface might change in the future"? And, If people are actually
into this idea, what adjustments should be made to the syntax?

Thanks in advance,

Andrew

-- 
http://www.apgwoz.com

-- 
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
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to