I'm trying to print out my binary tree but Clojure is giving me a hard time printing out the sequences properly.
So, I have a list of nodes '(1 2 3)
for example.
In each iteration I want to print out the node with a number of spaces before and after each element.
(defn spaces [n]
(apply str (repeat n " ")))
Great, this seems to work.
So, suppose I have a list of nodes
'(:a :b :c)
I want to print out on one line, with as said, the spaces.
(println (map #(str (spaces before) % (spaces (dec before))) nodes))
I have a list of items. Using the map I get a list of string objects. Great, so I can print them!
But this gives me this:
(clojure.lang.LazySeq@d0b37c31 clojure.lang.LazySeq@105879a9 clojure.lang.LazySeq@8de18242)
So I googled how to print lazy sequences and I came around to using print-str
command. According to the docs this prints to a string which then gets returned.
(println (print-str (map #(str (spaces before) % (spaces (dec before))) nodes)))
But this gives me this:
(clojure.lang.LazySeq@d0b37c31 clojure.lang.LazySeq@105879a9 clojure.lang.LazySeq@8de18242)
No change.. Hrm. Any help is greatly appreciated.
The
toString
method ofLazySeq
is called bystr
, and this avoids realizing the lazy sequence of values by opaquely showing the Object identity. Thepr-str
function calls theprint-dup
multimethod of an object, which is designed to get the version of a thing that could be understood by the reader (so for aLazySeq
the literal value that would make an equalLazySeq
).For pretty formatting of structures, do check out the
clojure.pprint
namespace which comes withclojure.core
, which haspprint
,print-table
, and various functions for customizing the behavior of pretty printing.