mirror of
https://github.com/kanaka/mal.git
synced 2024-09-11 13:55:55 +03:00
30 lines
788 B
Plaintext
30 lines
788 B
Plaintext
;; Examples for protocols.
|
|
|
|
(load-file "../lib/protocols.mal") ; defprotocol extend satisfies
|
|
|
|
(def! make-triangle (fn* [o a]
|
|
^{:type :shape/triangle} {:opposite o, :adjacent a}))
|
|
|
|
(def! make-rectangle (fn* [x y]
|
|
^{:type :shape/rectangle} {:width x, :height y}))
|
|
|
|
(defprotocol IDraw
|
|
(area [this])
|
|
(draw [this]))
|
|
|
|
(prn :false-> (satisfies? IDraw (make-triangle 5 5))) ;=> false
|
|
|
|
(extend :shape/rectangle
|
|
IDraw
|
|
{:area (fn* [obj] (* (get obj :width) (get obj :height)))
|
|
:draw (fn* [obj] (println "[]"))})
|
|
|
|
(extend :shape/triangle
|
|
IDraw
|
|
{:area (fn* [obj] (/ (* (get obj :opposite) (get obj :adjacent)) 2))
|
|
:draw (fn* [obj] (println " .\n.."))})
|
|
|
|
(prn :true-> (satisfies? IDraw (make-triangle 5 5))) ;=> true
|
|
|
|
(prn :area-> (area (make-triangle 5 4))) ;=> 10
|