One of the new features I propose to incorporate in an upcoming version of uLisp is support for Common Lisp’s format function. It probably won’t surprise you to learn that I’m not planning to implement the full ANSI specification of format! Instead I want to provide a subset that’s compatible with Common Lisp, and offers the features that will be most useful in embedded applications.
Here’s the proposed specification; please let me know if there are features of format I’ve omitted that you think would be desirable in uLisp:
Syntax: (format output controlstring arguments*)
Outputs its arguments formatted according to the format directives in the control string.
The output argument can be one of:
- nil: format returns the formatted output as a string.
- t: format prints the formatted output to the serial output.
- a stream: format prints the formatted output to the specified stream.
The control string can contain the following format directives:
|~a||ASCII||Output as princ would print it in human-readable format.|
|~s||Sexp||Output as prin1 would print it, with escape characters.|
|~d||Decimal||Decimal, as princ would print it.|
|~x||Hexadecimal||Hexadecimal with no leading zeros.|
|~g||General||General floating-point format, as princ would print it.|
|~~||Tilde||Just prints a ~.|
|~%||Newline||Outputs a newline.|
|~&||Newline||Outputs a newline unless already at the start of a line.|
Any other characters in the control string are just output unchanged.
> (format t "The battery is ~a V or ~a %." batt (* batt 20)) The battery is 4.75 V or 95 %.
If the argument is the wrong type for the directives ~d, ~x, or ~g the argument is output as if with ~a.
Each of the directives ~a, ~s, ~d, ~g, or ~x can include a width parameter after the tilde, and the output is padded with spaces to the specified width. If the output wouldn’t fit in the specified width it is output in full, and overflows the width. The ~a and ~s directives pad with spaces to the right; all the other directives pad with spaces to the left. In uLisp this is the only difference between ~a and ~d or ~g.
The width parameter will be useful for creating tabular data, or formatting output to be displayed on output devices such as seven-segment displays; for example:
> (format nil "~2d-~2d-~2d" hr min sec) " 1-45- 7"