30 lines
1.1 KiB
Plaintext
30 lines
1.1 KiB
Plaintext
;; A class is a named dyn map with a shape tag. A slot with no type holds
|
|
;; any value, and its constructor is the class's own name, positional.
|
|
(defclass point [x y])
|
|
(defclass circle [r])
|
|
|
|
;; CLOS-style: the generic states the return type once, and each method
|
|
;; dispatches on the class of its first argument.
|
|
(defgeneric area [self] dyn)
|
|
(defmethod area point [p] (* (get p :x) (get p :y)))
|
|
(defmethod area circle [c] (* 3 (get c :r) (get c :r)))
|
|
|
|
;; Clojure-style: the generic's body is the dispatch value, and a method
|
|
;; names the value it answers for. :else is the arm everything falls to.
|
|
(defmulti describe [x] dyn (get x :kind))
|
|
(defmethod describe :square [s] (get s :side))
|
|
(defmethod describe :else [s] "something else")
|
|
|
|
(defn main [] ()
|
|
(let [p (point 3 4)]
|
|
(println (area p))
|
|
(println (area (circle 2)))
|
|
;; A slot is a map key: get, put and has-key are how one is read.
|
|
(println (get p :y))
|
|
;; class-of answers the tag, and nil for anything that is not an instance.
|
|
(println (class-of p))
|
|
(println (class-of 7))
|
|
(println p)
|
|
(println (describe {:kind :square :side 9}))
|
|
(println (describe {:kind :blob}))))
|