user3710760
user3710760

Reputation: 567

Convert list of lists into string in Clojure

How do I convert a LazySeq which is a list of lists into a string that has the exact same structure and parantheses?

(def my-list (lazy-seq '((a b 0 1 x y) (a b 0 4 x y) (a b 0 3 x y) )))
(def string-list (print-to-string my-list ))

string-list
;; should return "((a b 0 1 x y) (a b 0 4 x y) (a b 0 3 x y) ))"
;; but returns "clojure.lang.LazySeq@72251662"

Upvotes: 0

Views: 327

Answers (2)

leetwinski
leetwinski

Reputation: 17859

for lazy sequences you can use print-str, which is alike simple print but writes the result to string.

user> (print-str my-list)
;;=> "((a b 0 1 x y) (a b 0 4 x y) (a b 0 3 x y))"

but beware, it obviously realizes the collection, and in case of infinite seq it would hang forever.

also you can override the print behaviour for any data type you want:

(defmethod print-method clojure.lang.LazySeq [data ^java.io.Writer w]
  (let [[firsts] (split-at 10 data)]
    (if (= 10 (count firsts))
      (.write w (str (seq firsts) " :: more"))
      (.write w (str (seq firsts))))))

user> (print-str (lazy-seq (range 1000)))
;;=> "(0 1 2 3 4 5 6 7 8 9) :: more"

Upvotes: 2

cfrick
cfrick

Reputation: 37008

If you want to keep the data as they are (or at least do your best with it), don't use str, but use pr-str. It might make no difference for simple things, but it will for more complex data structures.

E.g

user=> (pr-str (lazy-seq '((a b 0 1 x y) (a b 0 4 x y) (a b 0 3 x y) )))
"((a b 0 1 x y) (a b 0 4 x y) (a b 0 3 x y))"

Upvotes: 2

Related Questions