The out macro described is basically how Clojure’s str works. It takes any number of forms, discards the nils, calls toString on the rest, and then joins them
By relying on nil-punning, you can embed an expression and it will skip any result that evaluates to nil: ’(str “Hello” (when some-val “ World!”))returns “Hello World!” whensome-val` is truthy, and “Hello” when it is not.
returns “Hello World!” when
Haven’t used Clojure (yet!), thanks for sharing! In similar situations I often find myself pruning via apply and ,@:
(apply str `("Hello" ,@(when some-val " world!")))
;; Equivalent to:
(apply str (append '("Hello") (when some-val " world!")))
;; Of course, this only works if a no-op `when`
;; returns a value equivalent to the empty list
;; ( ie. nil/false = '() );
;; Otherwise we need to use an `if`, which doesn't feel as elegant...
(apply str `("Hello" ,@(if some-val " world!" '())))
PS: In a Lisp-2 the syntax would be (apply #'str ..., and, can I use back quotes in in-line monospace spans?
(apply #'str ...
I agree with the author’s criticism of format.
However, the out macro doesn’t address all of the problems that were identified.
Gilad Bracha uses the term “shadow world” to describe a DSL that reinvents features of a general purpose language (like conditionals and loops). https://gbracha.blogspot.com/2014/09/a-domain-of-shadows.html
It ought to be possible to create a string formatting API that is both pleasant to use and also free of shadow worlds and format strings.
[Comment removed by author]