【问题标题】:Closeable lazy-seq in ClojureClojure 中可关闭的惰性序列
【发布时间】:2022-09-23 04:08:40
【问题描述】:

我正在尝试创建一个也可以关闭的惰性序列。在 Clojure 中最干净的方法是什么? 预期用途(但这只是一个示例,我可以想到可关闭惰性序列的更多用法):

(with-open [lines (file-lines-seq file)]
   (consume (map do-stuff-to-line lines))) 

在这种情况下,这相当于:

(with-open [reader io/reader file]
    (consume (map do-stuff-to-line (line-seq file))))
  • 懒惰和关闭通常不能很好地协同工作。例如,您的预期用法展示了一个错误:因为 map 是惰性的,所以在您使用它的任何元素之前,seq 将被关闭。最好确保在 with-open 主体的动态范围内急切地处理事情。
  • 感谢@amalloy,我编辑了我的代码 sn-p 以添加一种使用序列的方法。它更多的是关于学习如何在惰性序列上添加行为而不是这个特定的例子。

标签: clojure


【解决方案1】:

设法通过这段精彩的代码获得预期的用途:

(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))
)))

如果有更丑陋的方法可以做到这一点,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 2010-12-08
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多