fahrenheit
2010-12-11
Introduction
This program converts a given temperature from degrees Fahrenheit to Celcius and the other way around. It introduces numbers, arithmetic, concatenation of strings, and conversion from numbers to strings.
Discussion
Numbers
The most straightforward way to work with numbers in Scheme is through number literals. These are numbers in integer (e.g. 32), fractional (e.g. 22/7), decimal (e.g. 1.1), or exponential notation (e.g. 1e9). Integer literals can also be specified in different bases by means of a prefix: #b for binary, #x for hexadecimal, and #o for octal.
To read in the temperature, we used the procedure read
. This procedure actually reads a Scheme expression, which means that it also accepts input
such as "foo", (newline), etc. Naturally, the rest of the program only makes sense if the user inputs a number. What happens if the input is
not a number is implementation dependent. Many implementations will start a run-time debugger, so that the error can be corrected. A run-time debugger is a very
valuable tool, but, unfortunately, the Scheme standard does not cover run-time debugging. The result is that all run-time debuggers work differently. Most of
them provide help, and if you just want to get out you can usually do so by entering (exit).
Arithmetic
Scheme uses the same syntax for performing arithmetic as for procedure calls. This means that the operator precedes the operands (prefix notation), rather than appears in between operands (infix notation). If you are used to infix notation, this can make arithmetical expressions in Scheme a bit hard to read at first. On the other hand, it makes Scheme's syntax more consistent and leaves no doubt about the order in which to evaluate an expression. The arithmetical operators supported by Scheme are + for addition, - for subtraction, * for multiplication, and / for division. All these take one or more arguments. You may want to experiment a bit to find out how they behave when given more or fewer than 2 arguments.
Formatted Output
The display procedure can display values of any type, but one call to display can be used to display only one value. To
display more than one value, you have two choices: either call display for each value, or assemble all values into one and then display that. Both approaches are
demonstrated in the example program. The first one should harbor no surprises, but the second one requires some additional explanation. We use
string-append
to assemble the values we want to display into one string. This procedure takes one or more strings, concatenates them, and
returns the result. Now, some of the values we want to pass in are not strings, but numbers. These, we convert to strings using number->string
.