Clojure打印惰性序列

15
我想打印出我的二叉树,但Clojure在正确打印序列方面使我很困扰。
所以,我有一个节点列表'(1 2 3)
在每次迭代中,我想打印出每个元素前后带有一定数量的空格的节点。
(defn spaces [n]
  (apply str (repeat n " ")))

很好,这看起来可行。

那么,假设我有一个节点列表'(:a :b :c),我想要将它们打印在一行上,并带有空格。

(println (map #(str (spaces before) % (spaces (dec before))) nodes))

我有一个项目清单。使用map函数我得到了一组字符串对象。非常好,我可以打印它们!

但这会给我这个:

(clojure.lang.LazySeq@d0b37c31 clojure.lang.LazySeq@105879a9 clojure.lang.LazySeq@8de18242)

于是我谷歌了一下如何打印惰性序列,然后我发现可以使用print-str命令。根据文档,这将打印到一个字符串中并返回该字符串。

(println (print-str (map #(str (spaces before) % (spaces (dec before))) nodes)))

但这给了我这个:

(clojure.lang.LazySeq@d0b37c31 clojure.lang.LazySeq@105879a9 clojure.lang.LazySeq@8de18242)

没有改变... 嗯。非常感谢任何帮助。

1个回答

32
user> (str (map inc (range 10)))
"clojure.lang.LazySeq@c5d38b66"
user> (pr-str (map inc (range 10)))
"(1 2 3 4 5 6 7 8 9 10)"
LazySeqtoString 方法是由 str 调用的,这避免了通过不透明地显示对象标识来实现懒惰值序列。 pr-str 函数调用对象的 print-dup 多方法,该方法旨在获取读者可以理解的事物的版本(因此对于 LazySeq 来说,是使相等的 LazySeq 的字面值)。
为了美观的格式化结构,请确保查看随附的 clojure.coreclojure.pprint 命名空间,其中包含 pprintprint-table 和各种自定义美观打印行为的函数。
user> (require '[clojure.pprint :as pprint :refer [pprint print-table]])
nil
user> (pprint [:a [:b :c :d [:e :f :g] :h :i :j :k] :l :m :n :o :p :q [:r :s :t :u :v] [:w [:x :y :z]]])
[:a
 [:b :c :d [:e :f :g] :h :i :j :k]
 :l
 :m
 :n
 :o
 :p
 :q
 [:r :s :t :u :v]
 [:w [:x :y :z]]]
nil
user> (print-table (map #(let [start (rand-int 1e6)] (zipmap % (range start (+ start 10)))) (repeat 5 [:a :b :c :d :e :f :g :h :i :j])))

|     :a |     :c |     :b |     :f |     :g |     :d |     :e |     :j |     :i |     :h |
|--------+--------+--------+--------+--------+--------+--------+--------+--------+--------|
| 311650 | 311652 | 311651 | 311655 | 311656 | 311653 | 311654 | 311659 | 311658 | 311657 |
|  67627 |  67629 |  67628 |  67632 |  67633 |  67630 |  67631 |  67636 |  67635 |  67634 |
| 601726 | 601728 | 601727 | 601731 | 601732 | 601729 | 601730 | 601735 | 601734 | 601733 |
| 384887 | 384889 | 384888 | 384892 | 384893 | 384890 | 384891 | 384896 | 384895 | 384894 |
| 353946 | 353948 | 353947 | 353951 | 353952 | 353949 | 353950 | 353955 | 353954 | 353953 |
nil

非常理解!谢谢! - Christophe De Troyer
我觉得 str 函数似乎无法避免实现惰性序列: user> (str (map #(do (println %) (inc %)) (range 10))) 结果为 0 1 2 3 4 5 6 7 8 9 "clojure.lang.LazySeq@c5d38b66" - Oliver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接