2014-11-21 67 views
2

在Clojure中將數據結構寫入磁盤的最習慣的方式是什麼,所以我可以用edn/read讀回它?我嘗試以下,建議在Clojure cookbook將大數據結構作爲EDN寫入clojure中的磁盤

(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))來完成,但後來我必須在序列的開頭和結尾手動添加parens以獲得所需的結果。

回答

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呼叫時檢查當前的綁定。

+1

對於大型數據結構,使用'(pr-str)'是個好主意;它會將它打印到內存中的字符串,這可能比原始結構佔用更多內存。我會簡單地在OP代碼中添加'* print-length *'nil綁定到綁定向量。 – 2014-11-21 15:19:10

+0

我的'* print-length *'被設置爲100.罪魁禍首似乎是emacs live。見http://stackoverflow.com/questions/20300594/clojure-pr-str-cutting-off-lists-100-items – pholz 2014-11-21 15:22:33

+0

@DiegoBasch好點。編輯。 – Kyle 2014-11-21 15:22:37