[英]Closeable lazy-seq in Clojure
I'm trying to create a lazy-seq which is also closeable.我正在尝试创建一个也可以关闭的惰性序列。 What would be the cleanest way to do that in Clojure?
在 Clojure 中最干净的方法是什么? Intended usage (but it's just one example, I can think of more usages for a closeable lazy sequance):
预期用途(但这只是一个示例,我可以想到可关闭惰性序列的更多用法):
(with-open [lines (file-lines-seq file)]
(consume (map do-stuff-to-line lines)))
Which in this case would be equivalent to:在这种情况下,这相当于:
(with-open [reader io/reader file]
(consume (map do-stuff-to-line (line-seq file))))
Managed to get the intended usage with this wonderful piece of code:设法通过这段精彩的代码获得预期的用途:
(defn file-lines-seq [file]
(let [reader (clojure.java.io/reader file)
lines-seq (line-seq reader)]
(reify
Closeable
(close [this] (.close reader))
ISeq
(first [this] (.first lines-seq))
(next [this] (.next lines-seq))
(more [this] (.more lines-seq))
(cons [this var1] (.cons lines-seq var1))
(count [this] (.count lines-seq))
(empty [this] (.empty lines-seq))
(equiv [this var1] (.equiv lines-seq var1))
(seq [this] (.seq lines-seq))
)))
If there's a less ugly way to do this, please let me know.如果有更丑陋的方法可以做到这一点,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.