Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This script produces some samples of how to use formatting
;; This script will generate a formatting demo
;; Call it with a filename to dump demo to file
(ns demo.formatting
(:use [clojure.contrib.duck-streams :only [with-out-writer]]
[clojure.string :only [join]])
(:import java.util.Date))
(defn print-demo-code [fmt & args]
(printf "%-50s ;=> %s%n"
(format "(format %s %s)"
(pr-str fmt)
(join \space
(map #(if (= Date (type %))
"(Date.)"
(pr-str %))
args)))
(apply (partial format fmt)
args)))
(defn demo-samples []
(let [now (Date.)]
(doseq [sample [["Hello, %s!" "world"]
["%s = %s" "SomeKey" "SomeValue"]
["%1$s + %1$s = %2$s" 2 4]
["e = %+.4f" Math/E]
[":%-20s:" "right padding"]
[":%20s:" "left padding"]
["%b %b %b %b" true false nil "something"]
["#%02x%02x%02x;" 255 0 125]
["%s" now]
["Offset: %tz" now]
["Time zone: %tZ" now]
["%1$tH:%1$tM:%1$tS" now]
["%1$tl:%1$tM %1$tp" now]
["Unix time: %ts" now]
["%1$td/%1$tm-%1$ty" now]
["%1$td. %1$tb %1$ty" now]
["%1$td. %1$tB %1$tY" now]
["ISO 8601: %tF" now]]]
(apply print-demo-code
sample))))
(demo-samples) ; First, output to standard out
; Then, if file is specified, print to it as well
(when (seq? *command-line-args*)
(let [f (first *command-line-args*)]
(println "Dumping to file" f)
(with-out-writer f
(demo-samples))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment