Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clojure: apply println to multiple strings scrambles output

In Clojure 1.11, I’m evaluating this term:

(apply println "foo\n" "bar\n" "baz\n")

I expect the following output:

foo
bar
baz

However, I’m getting this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foo
 bar
 b a z

The first line is as I need it. The second line contains a leading space. The third line has a superfluous space before each letter.

Why is behaving apply/println like that, and how can I get the desired output?

>Solution :

Leading spaces come from the fact that println adds spaces when printing its arguments. E.g. try (println 1 2 3) – you’ll get 1 2 3 in the output.

The last line comes out as it does because you’re using apply. apply treats the last argument as a collection as passes its items as separate arguments to the target function. So in this case you most likely don’t need apply at all.

To achieve what you want, you should use something like (run! print ["foo\n" "bar\n" "baz\n"]). Or use println and don’t add \n yourself since println does that for you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading