Conditional Output
GNU Common Lisp
~v^
The up-and-out directive ~^
is most commonly used in a list formatting operation to terminate after the last list item. However, it can also be used with a v
modifier to consume an argument, in which case it terminates if that argument is zero. This is particularly useful for dealing with the zero produced by dotimes
.
(loop as n from 1 to 10 do(format t"~d~%"n))
(dotimes(n 11)(if(> n 0)(format t"~d~%"n)))
(dotimes(n 11)(format t"~v^~d~%"n n))
format(condition)
The first argument to format
can be one of t
, nil
a.k.a. ()
, or a stream. If passed t
, it will output to stdout
, if nil
it will return the formatted output as a string. This can be used conditionally output. The above example could be written equally as short as:
(dotimes(n 11)(format(> n 0)"~d~%"n))
If a value was output, the return value will be nil
. Because of this, it can also be used as the terminating condition for a do
loop:
(do((n 11))((<(decf n)1))(format t"~d~%"n))
(do((n 11))((format(>(decf n)0)"~d~%"n)))
~[...~]
The conditional formatter consumes an argument, and selects a formatting string from a list by index. A common use case is with the default formatter ~:;
to select between zero and not zero.
(dotimes(n 11)(format t"~v^~[~r~:;~d~]~%"n(mod n 3)n))
Conditional formatters can also be nested, in which case each will consume an argument in turn.
~&
In each of the examples above, ~%
is used to emit a newline. In most cases, this could be replaced by a literal newline. Another option is to use ~&
, which will emit a newline if and only if the output cursor is not at the start of a line, a.k.a. a fresh-line
.
Both ~%
and ~&
can also take an argument, with a v
modifier or as a constant, and will produce as many newlines. They will also both happily accept a negative argument, in which case they emit nothing.
External References
Practical Common Lisp
18. A Few FORMAT Recipes
Common Lisp the Language, 2nd Edition
22.3.3. Formatted Output to Character Streams
3https://xkcd.com/297/ – James – 2016-05-10T23:50:39.017
1
Do you imagine these will be distinct from the tips for golfing in Scheme and Racket?
– Alex A. – 2016-05-11T00:09:53.0771I would advise using tinylisp, a smaller, stripped-down version of Lisp for your golfing pleasure. – ckjbgames – 2017-02-01T23:12:55.037