Last active
August 29, 2015 13:56
-
-
Save jarppe/9346413 to your computer and use it in GitHub Desktop.
...because C++ had that one good thing
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
(defmacro << [& body] | |
(let [[fmt args] (loop [fmt "" | |
args [] | |
[p & more] body] | |
(if p | |
(cond | |
(and (symbol? p) (starts-with (name p) "%")) (recur (str fmt (name p)) (conj args (first more)) (rest more)) | |
(symbol? p) (recur (str fmt "%s") (conj args p) more) | |
(string? p) (recur (str fmt (str p)) args more) | |
:else (recur (str fmt "%s") (conj args p) more)) | |
[fmt args]))] | |
`(format ~fmt ~@args))) | |
(= (<< "hello " %s "world" ", PI is " %.2f 3.14159) (format "hello %s, PI is %.2f" "world" 3.14159))) ;=> true | |
(let [s "foo" | |
i 42 | |
f 3.14159] | |
(= (<< %s s ", " %d i ", " %.2f f) (format "%s, %d, %.2f" s i f)) ;=> true | |
(= (<< s ", " s) "foo, foo") ;=> true | |
(= (<< "1 + 2 = " (+ 1 2)) "1 + 2 = 3")) ;=> true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment