FORMAT in Common Lisp writes to a DESTINATION

Most uses of FORMAT either supply a stream or NIL as the destination argument. However, FORMAT can also take a string with a fill-pointer (i.e. a “non-simple string”). It behaves like you’d want, unless you want very odd behaviour. An example:

CL> (setf ns (make-array 0 :element-type 'character :adjustable t :fill-pointer t))
=> ""
CL> (format ns "Hello, ")
=> NIL
CL> ns
=> "Hello, "
CL> (format ns "world!")               
=> NIL
CL> ns
=> "Hello, world!"

If you’re just construing an output string in piecemeal fashion before returning, something like WITH-OUTPUT-TO-STRING probably suffices.

But I’ve found the above approach of FORMATting a non-simple string useful when e.g. construing a message in asynchronous fashion while providing partial progress. Certainly seems easier to read a string (even a non-simple one) multiple times than to read a stream multiple times.

Click Here to Leave a Comment Below