Created
April 7, 2011 19:09
-
-
Save tormaroe/908464 to your computer and use it in GitHub Desktop.
This script produces some samples of how to use formatting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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