Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pretty print a quoted list in clojure?

Tags:

clojure

Given a list like:

(quote (do (println "Hello") (println "Goodbye")))

: how can I turn this into a nicely formatted string which will output something like:

(do
  (println "Hello") 
  (println "Goodbye")
)
like image 200
yazz.com Avatar asked Aug 04 '13 14:08

yazz.com


2 Answers

Use clojure.pprint/write with clojure.pprint/code-dispatch:

(clojure.pprint/write '(do (println "Hello") (println "Goodbye"))
                      :dispatch clojure.pprint/code-dispatch)

For that small amount of code you won't get new-lines. But a call like this

(clojure.pprint/write '(do (println "Hello") (println "Goodbye") (println "Hey, you left me out!"))
                      :dispatch clojure.pprint/code-dispatch)

Returns

=> (do
     (println "Hello")
     (println "Goodbye")
     (println "Hey, you left me out!"))

To catch that as a string wrap the call in (with-out-str ...)

like image 127
Leon Grapenthin Avatar answered Oct 20 '22 17:10

Leon Grapenthin


As a significantly more performant alternative to clojure.pprint, you might want to try Brandon Bloom's fipp:

;; add [fipp "0.4.0"] to :dependencies
(require '[fipp.edn :as fipp])

(fipp/pprint '(do (println :foo) (println :bar) (println :quux))
             {:width 30}) ; force wrapping despite small size of data
;; printed output:
(do
 (println :foo)
 (println :bar)
 (println :quux))

Unfortunately, Fipp does not yet support code-dispatch.

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

Michał Marczyk