Clojure,Aspects,Defprotocol,Defrecord

时间:2012-11-18 04:47:35

标签: clojure

(defprotocol IAnimal "IAnimal"
  (report [o]
    (println (type o) " reporting.\n")
    (inner-report o)
    (println (type o) " out.\n")))

(defrecord Dog [] IAnimal
  (inner-report [o]
    (println "Woof Woof.\n")))

(defrecord Cat [] IAnimal
  (inner-report [o]
    (println "Meow Meow.\n")))

(defrecord Vampire [] IAnimal
  (inner-report [o]
    (println "I don't sparkle.\n")))

现在,我希望输出:

Dog reporting.
Woof Woof.
Dog out.
Cat reporting.
Meow Meow.
Cat out.
Vampire reporting.
I don't sparkle.
Vampire out.

不幸的是,由于上面的代码没有编译,所以不会发生这种情况。实现“这个”的最佳方式是什么?

在哪里用“this”,我的意思是我有一些函数,我希望成为协议的一部分,我希望对所有记录都有一个实现,我希望这个函数能够访问记录的专用函数实施

(这样做的clojure方式是什么?)

1 个答案:

答案 0 :(得分:5)

协议就像Java接口,它们无法为其方法提供实现。但这有效:

(defn report [o]
  (println (type o) " reporting.\n")
  (inner-report o)
  (println (type o) " out.\n"))

(defprotocol IAnimal
  "the animal protocol"
  (inner-report [o] "a report"))

(defrecord Dog []
  IAnimal
  (inner-report [o]
    (println "Woof Woof.\n")))

(defrecord Cat []
  IAnimal
  (inner-report [o]
    (println "Meow Meow.\n")))

(defrecord Vampire []
  IAnimal
  (inner-report [o]
    (println "I don't sparkle.\n")))

(report (new Cat))
;; user.Cat reporting.
;; Meow Meow.
;; user.Cat out.