Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Primitive Arrays in Clojure

I am at the REPL, and I create a java array:

=> (def arr (double-array [1 2 3]))

Of course, if I want to look at my arr, I get:

=> arr
#<double[] [D@2ce628d8>

Is there anything I can do that will make arrays of java primitives print like clojure's persistentVectors?

=> arr
[1.0 2.0 3.0]

I know I could wrap my arrays in some sort of nice printing function (which is what I currently do), but this is a pain in cases, for example, where the vectors are part of a map:

=> my-map
{"1" #<double[] [D@47254e47>, "2" #<double[] [D@11d2625d>}
like image 593
charleslparker Avatar asked Dec 05 '11 19:12

charleslparker


2 Answers

Would something as simple as the following do?

user=> (seq arr)
(1.0 2.0 3.0)

If it's only for the REPL, then perhaps the technical semantics don't matter.

Update

It turns out that pretty print (pprint) works just fine with your map of vectors:

user=> (def my-map {"1" (double-array [1 2 3])
                    "2" (double-array [1 2 3])})
#'user/my-map
user=> (pprint my-map)
{"1" [1.0, 2.0, 3.0], "2" [1.0, 2.0, 3.0]}

Final Update: From the linked Google Groups discussion in the comments

Questioner found an answer he liked in a discussion paraphrased below:

> Is there any way to make the Clojure repl pretty-print by default?

Try:

(clojure.main/repl :print pprint)

> Thank you! That is exactly what I needed.

like image 58
Scott Avatar answered Sep 23 '22 02:09

Scott


There is always the java interop solution:

(java.util.Arrays/toString arr)

So you would have

(map #(java.util.Arrays/toString (val %)) my-map)
like image 45
Julien Chastang Avatar answered Sep 27 '22 02:09

Julien Chastang