display vs write

This is not exactly rocket science, but I just read up on the difference between Scheme’s display and write functions. :-)

R5RS says about write: “Writes a written representation of obj to the given port. Strings that appear in the written representation are enclosed in doublequotes, and within those strings backslash and doublequote characters are escaped by backslashes. Character objects are written using the #\ notation.”

And about display: “Writes a representation of obj to the given port. Strings that appear in the written representation are not enclosed in doublequotes, and no characters are escaped within those strings. Character objects appear in the representation as if written by write-char instead of by write.”

Also: “Rationale: Write is intended for producing machine-readable output and display is for producing human-readable output. Implementations that allow “slashification” within symbols will probably want write but not display to slashify funny characters in symbols.”

The difference is maybe best demonstrated by an example:

> (define s "one\ntwo\n")
> (display s)
one
two
> (write s)
"one\ntwo\n"

Hmm… a function for machine-readable output, versus one for human-readable output. Sound familiar? Compare Python’s str and repr (or, if you wish, the __str__ and __repr__ methods).

This explains why formatting functions like printf accept a directive that writes an argument (~s), *and* one that displays it (~a). That makes sense now.

In any case, I’ve been using print a lot, which seems to be the same as display, followed by a newline.

Comments are closed.