在Clojure中,如何在我自己的记录和类型上实现标准的Clojure集合接口?

时间:2011-01-03 17:10:42

标签: clojure

我希望创建一个表示数据库表的抽象,但可以使用所有常用的Clojure seq和conj以及所有那些花哨的东西来访问它。我需要添加一个协议吗?

1 个答案:

答案 0 :(得分:15)

是。该协议由Java接口clojure.lang.ISeq定义。您可能希望扩展clojure.lang.ASeq,它提供了它的抽象实现。

以下是一个示例:资源的seq抽象,可以关闭,并在seq结束时自动关闭。 (未经过严格测试)

(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)))
相关问题