formatter
formatter Macro
Syntax:
formatter control-string → function
Arguments and Values:
control-string—a format string; not evaluated.
function—a function.
Description:
Returns a function which has behavior equivalent to:
#’(lambda (*standard-output* &rest arguments)
(apply #’format t control-string arguments)
arguments-tail)
where arguments-tail is either the tail of arguments which has as its car the argument that would be processed next if there were more format directives in the control-string, or else nil if no more arguments follow the most recently processed argument.
Examples:
(funcall (formatter "~&~A~A") \*standard-output\* ’a ’b ’c)
▷ AB
→ (C)
(format t (formatter "~&~A~A") ’a ’b ’c)
▷ AB
→ NIL
Exceptional Situations:
Might signal an error (at macro expansion time or at run time) if the argument is not a valid format string.
See Also:
formatExpanded Reference: formatter
Basic Usage
formatter compiles a format control string into a function at macro-expansion time. The resulting function takes a stream as its first argument, followed by the format arguments.
(funcall (formatter "~A + ~A = ~A") *standard-output* 2 3 5)
.. 2 + 3 = 5
=> NIL
Using with format
The function returned by formatter can be passed to format in place of a string.
(format t (formatter "Hello, ~A!~%") "world")
.. Hello, world!
..
=> NIL
(format nil (formatter "~D items") 42)
=> "42 items"
Return Value -- Remaining Arguments
When called directly with funcall, the function returns the tail of the argument list that was not consumed by the format string.
(funcall (formatter "~A ~A") *standard-output* 'x 'y 'z 'w)
.. X Y
=> (Z W)
Pre-compiled for Efficiency
formatter is useful when the same format string is used repeatedly, since it compiles the format string once at compile time rather than interpreting it each time.
(let ((fmt (formatter "Item: ~A, Qty: ~D~%")))
(with-output-to-string (s)
(funcall fmt s "Widget" 10)
(funcall fmt s "Gadget" 5)))
=> "Item: Widget, Qty: 10
Item: Gadget, Qty: 5
"
Using with set-pprint-dispatch
formatter can produce functions suitable for use with set-pprint-dispatch and with ~/...~/ format directives.
(let ((*print-pprint-dispatch* (copy-pprint-dispatch))
(*print-pretty* t))
(set-pprint-dispatch '(cons (eql :pair))
(formatter "~:<~W ~:_~W ~:_~W~:>"))
(write-to-string '(:pair "key" "value")))
=> "(:PAIR \"key\" \"value\")"