0

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"
3
  • it's just (str my-list) Commented Jun 26, 2020 at 7:47
  • oh sorry I meant for a LazySeq this doesn't work Commented Jun 26, 2020 at 7:57
  • 1
    could you please update your question with the actual case then ) Commented Jun 26, 2020 at 8:00

2 Answers 2

2

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))"
Sign up to request clarification or add additional context in comments.

1 Comment

cfrick mentioned pr and @leetwinski mentioned print. The difference was the subject of stackoverflow.com/questions/21136766/….
2

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.