On 22.01.2009, at 09:30, Konrad Hinsen wrote: > Not that I know. I have been searching for a while, and ended up > using my own tag attached to the struct as metadata. In clojure.zip > there is a similar use of metadata: methods are implemented as > functions passed in the metadata.
After a quick look at the Clojure source code, I had an idea for
implementing something better, and did it :-) A patch is attached.
This patch adds:
- a Java method on structmaps that returns the structure basis (the
object created by defstruct).
- a few Clojure functions to work with this:
(struct-basis x) returns the structure basis of structmap x
(struct? x) returns true if x is a structmap
(struct? x s) returns true if x is a structmap with basis s
(struct-basis? s) returns true if s it a structure basis
- a minimal patch to derive that allows structure basis objects to be
used in hierarchies
At the end of this message is a simple illustration of what can be
done with these changes. Any feedback is welcome of course!
Konrad.
(defstruct rectangle :x :y :w :h)
(defstruct circle :x :y :r)
(defmulti area struct-basis)
(defmethod area rectangle
[r]
(* (:w r) (:h r)))
(defmethod area circle
[c]
(let [r (:r c)]
(* (. Math PI) r r )))
(area (struct rectangle 0. 0. 2. 3.))
(area (struct circle 0. 0. 1.))
(derive rectangle ::shape)
(derive circle ::shape)
(defmulti center struct-basis)
(defmethod center ::shape
[s]
[(:x s) (:y s)])
(defmethod center rectangle
[r]
(let [{:keys [x y w h]} r]
[(/ (+ x w) 2) (/ (+ y h) 2)]))
(center (struct rectangle 0. 0. 2. 3.))
(center (struct circle 0. 0. 1.))
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
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
-~----------~----~----~----~------~----~------~--~---
structs_in_multimethods.diff
Description: Binary data
