Clojure印刷懒人序列

时间:2014-05-01 10:21:17

标签: clojure lazy-sequences

我正在尝试打印出我的二叉树,但是Clojure让我很难正确地打印出序列。

因此,我有一个节点列表'(1 2 3),例如。

在每次迭代中,我想在每个元素之前和之后打印出具有多个空格的节点。

(defn spaces [n]
  (apply str (repeat n " ")))

太好了,这似乎有效。

所以,假设我有一个nodes '(:a :b :c)的列表,我想在一行打印出来,如上所述,空格。

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

我有一个项目列表。使用地图我得到一个字符串对象列表。好的,所以我可以打印出来!

但是这给了我这个:

(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 个答案:

答案 0 :(得分:24)

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

toString的{​​{1}}方法由LazySeq调用,这避免了通过不透明地显示对象标识来实现延迟的值序列。 str函数调用对象的pr-str多方法,该方法旨在获取读者可以理解的事物的版本(因此对于print-dup的文字值将是LazySeq做一个相等的LazySeq)。

对于结构的漂亮格式,请查看clojure.pprint附带的clojure.core命名空间,其中包含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
相关问题