[英]In Clojure how can I implement standard Clojure collection interfaces on my own records and types?
I wish to create an abstraction which represents a database table, but which can be accessed using all the usual Clojure seq and conj and all that fancy stuff. 我希望创建一个表示数据库表的抽象,但可以使用所有常用的Clojure seq和conj以及所有那些花哨的东西来访问它。 Is there a protocol I need to add?
我需要添加一个协议吗?
Yes. 是。 The protocol is defined by the Java interface
clojure.lang.ISeq
. 该协议由Java接口
clojure.lang.ISeq
定义。 You may want to extend clojure.lang.ASeq
which provides an abstract implementation of it. 您可能希望扩展
clojure.lang.ASeq
,它提供了它的抽象实现。
Here is an example: a seq
abstraction of a resource which is closable and is closed automatically when the seq
ends. 下面是一个示例:资源的
seq
抽象,可以关闭,并在seq
结束时自动关闭。 (Not rigorously tested) (未经过严格测试)
(deftype CloseableSeq [delegate-seq close-fn]
clojure.lang.ISeq
(next [this]
(if-let [n (next delegate-seq)]
(CloseableSeq. n close-fn)
(.close this)))
(first [this] (if-let [f (first delegate-seq)] f (.close this)))
(more [this] (if-let [n (next this)] n '()))
(cons [this obj] (CloseableSeq. (cons obj delegate-seq) close-fn))
(count [this] (count delegate-seq))
(empty [this] (CloseableSeq. '() close-fn))
(equiv [this obj] (= delegate-seq obj))
clojure.lang.Seqable
(seq [this] this)
java.io.Closeable
(close [this] (close-fn)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.