【问题标题】:write large data structures as EDN to disk in clojure在 clojure 中将大型数据结构作为 EDN 写入磁盘
【发布时间】:2014-11-21 15:06:16
【问题描述】:

在 Clojure 中将数据结构写入磁盘的最惯用方法是什么,以便我可以使用 edn/read 将其读回?按照Clojure cookbook中的建议,我尝试了以下方法:

(with-open [w (clojure.java.io/writer "data.clj")]
  (binding [*out* w]
    (pr large-data-structure)))

但是,这只会写入前 100 个项目,然后是“...”。我也尝试了(prn (doall large-data-structure)),得到了相同的结果。

我已经设法通过逐行编写(doseq [i large-data-structure] (pr i)) 来做到这一点,但是我必须在序列的开头和结尾手动添加括号才能获得所需的结果。

【问题讨论】:

    标签: clojure edn


    【解决方案1】:

    您可以通过*print-length* 控制集合中打印的项目数

    考虑使用spit而不是手动打开编写器和pr-str而不是手动绑定到*out*

    (binding [*print-length* false]
      (spit "data.clj" (pr-str large-data-structure))
    

    从评论编辑:

    (with-open [w (clojure.java.io/writer "data.clj")]
      (binding [*print-length* false
                *out* w]
        (pr large-data-structure)))
    

    注意*print-length* 的根绑定为nil,因此您不需要在上面的示例中绑定它。我会在您最初调用 pr 时检查当前绑定。

    【讨论】:

    • 对于大型数据结构,使用(pr-str) 是个坏主意;它会将其打印到内存中的字符串中,这可能会比原始结构占用更多的内存。我只需将*print-length* nil 绑定添加到 OP 代码中的绑定向量。
    • 我的*print-length* 设置为100。罪魁祸首似乎是emacs live。见stackoverflow.com/questions/20300594/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2017-10-12
    • 2014-06-14
    相关资源
    最近更新 更多