defprotocol, deftype, defrecord

clojure久しぶりに書いています。 defprotocolとかよく忘れるのでメモがてら貼っておきます。 protocolってthisが第一引数なのが前提なんですよね。このせいでモナドのreturnが定義できないってのに泣いた覚えが。

(ns myns)

(deftype MyString [value])
(deftype MyNumber [value])
(defrecord MyRecord [value])

(defprotocol print-protocol
  (my-print [x]))

(extend-protocol print-protocol
  MyString
  (my-print [x] (println (str "MyString: " (.value x))))
  MyNumber
  (my-print [x] (println (str "MyNumber: " (.value x))))
  MyRecord
  (my-print [x] (println (str "MyRecord: " (.value x)))))


(def s1 (MyString. "Hello"))
(def n1 (MyNumber. 12345))
(my-print s1)
(my-print n1)

(def s2 (->MyString "Hello"))
(my-print s2)

(def r1 (MyRecord. "record"))
(:value r1)
(.value r1)
(my-print r1)

(def r2 (->MyRecord "record2"))
(:value r2)
(.value r2)
(my-print r2)

(def r3 (map->MyRecord {:value "record3"}))
(:value r3)
(.value r3)
(my-print r3)