Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Print the contents of a vector

Tags:

clojure

In Clojure, how do you print the contents of a vector? (I imagine to the console, and usually for debugging purposes). If the answer can be generalized to any Seq that would be good.

Edit: I should add that it should be a simple function that gives output that looks reasonable, so prints an item per line - so can be easily used for debugging purposes. I'm sure there are libraries that can do it, but using a library really does seem like overkill.

like image 866
Chris Murphy Avatar asked Sep 07 '15 04:09

Chris Murphy


2 Answers

I usually use println. There are several other printing functions that you might want to try. See the "IO" section of the Clojure cheatsheet.

This isn't Java. Just print it, and it will look OK.

You can also use clojure.pprint/pprint to pretty-print it. This can be helpful with large, complex data structures.

These methods work for all of the basic Clojure data structures.

Exception: Don't print infinitely long lazy structures such as what (range) returns--for obvious reasons. For that you may need to code something special.

like image 185
Mars Avatar answered Sep 28 '22 03:09

Mars


This works for me:

(defn pr-seq
  ([seq msg]
   (letfn [(lineify-seq [items]
                        (apply str (interpose "\n" items)))]
     (println (str "\n--------start--------\n"
                   msg "\nCOUNT: " (count seq) "\n"
                   (lineify-seq seq) "\n---------end---------"))))
  ([seq]
    (pr-seq seq nil)))

Example usages:

(pr-seq [1 2 3])
(pr-seq (take 20 blobs) (str "First 20 of " (count blobs) " Blobs")))
like image 35
Chris Murphy Avatar answered Sep 28 '22 02:09

Chris Murphy