Programming Corner from Icon Newsletter 41
March 15, 1993; Icon Version 8
It's common practice when debugging a program to insert a write()
expression where trouble is expected, as in
write("x=", x)
That works well enough as long as you can be sure of the type of x
and that it's something write()
can convert to a string. But
it's not very discriminating -- you get a blank line if x
is
an empty string, an empty cset, or null. And there's no way to tell whether
x
is an integer or a string that happens to consist of digits.
And if x
happens to be something that can't be converted to
a string, such as a list, you get a run-time error for your trouble.
The function image()
takes care of all of these problems. In
the first place, it's safe: image(x)
always produces a string,
regardless of the type of x
. Furthermore, image(x)
is designed so that you can tell what the type of x
is. Strings
are enclosed in double quotes, csets in single quotes, while integers and
real numbers are not quoted. A value that corresponds to a keyword is imaged
with the keyword name. For example, the image of the null value is &null
.
In the case of structures, the type, a serial number, and the size are given.
For example, the image of an empty list might be list_15(0)
.
The 15
is its serial number; the fifteenth list created since
beginning of program execution. The number in parentheses is the size, zero
in this case.
image()
has other useful features. For example, the image of
a value of type procedure shows whether it's built in (function) or declared
(procedure). There are other things you might want to know about different
kinds of images. In any event, it's worth casting diagnostic output in a
form such as
write("x=", image(x))
Incidentally, several very capable extensions to the built-in image()
function are included in the Icon program library. See fullimag.icn
,
image.icn
, and ximage.icn
.
Icon home page