Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure sprintf?

Tags:

printf

clojure

There is printf. It prints directly to stdout.

How about sprintf, which formats the same way as printf, but returns a string with no side-effects?

like image 549
qrest Avatar asked Aug 28 '10 19:08

qrest


3 Answers

Consider using the with-out-str macro:

(with-out-str
    (print x))

Or just call java.lang.String's format method:

(String/format "%d" 3)
like image 131
bendin Avatar answered Oct 22 '22 04:10

bendin


In Clojure it's called format and resides in clojure.core: printf is equivalent to (comp print format).

like image 20
Michał Marczyk Avatar answered Oct 22 '22 04:10

Michał Marczyk


You should check out cl-format, in the clojure.pprint lib. It's a port of Common Lisp's FORMAT function. It can do things that Java's printf can't do, like conditionals, iterating over seqs, etc.

To answer your question, with cl-format, a first argument of nil will return a string; a first argument of true will print to STDOUT.

user> (cl-format nil "~{~R~^, ~}" [1 2 3 4])
"one, two, three, four"

Note that if format didn't already exist in Clojure, you could also capture the output from Clojure's printf like this:

user> (with-out-str (printf "%s" :foo))
":foo"

with-out-str is helpful when a library only provides a function that prints to STDOUT and you want to capture the output instead. I've run across Java libraries that do this.

like image 31
Brian Carper Avatar answered Oct 22 '22 04:10

Brian Carper