Clojure,Aspects,Defprotocol,Defrecord [英] Clojure, Aspects, Defprotocol, Defrecord
本文介绍了Clojure,Aspects,Defprotocol,Defrecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(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.
不幸的是,这并不会发生,因为上面的代码不能编译。什么是实现这个的最好方法?
Unfortuantely, this does not happen since the above code does not compile. What is the best way to achieve "this" ?
在这里,我的意思是我有一些功能,我想成为协议的一部分,我想对所有记录有一个实现它,我希望这个函数可以访问记录实现的专门函数。
Where by "this", I mean I have some function that I want to be part of a protocol, I want to have one implementation of it for all records, and I want this function to have access to specialized functions that records implement.
(什么是clojure这样做? )
(What is the clojure way of doing this?)
推荐答案
协议就像Java接口,他们不能为他们的方法提供实现。但这个工程:
Protocols are like Java interfaces, they cannot provide implementation for their methods. But this works:
(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.
这篇关于Clojure,Aspects,Defprotocol,Defrecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文