Prologue: How to Program
When you were a small child, your parents probably taught you to count and later to perform simple calculations with your fingers: “1 + 1 is 2”; “1 + 2 is 3”; and so on. Then they would ask “what’s 3 + 2” and you would count off the fingers of one hand. They programmed, and you computed. And in some way, that’s really all there is to programming and computing.
Start DrRacket and select “Choose language” from the “Language” menu. This brings up a dialog listing “Teaching Languages” for “How to Design Programs” (and possibly other books). Click “Beginning Student Language” and “OK” to set up DrRacket for this chapter.
Now you’re switching roles. You program, and the computer is a child. Of course, you start with the simplest of all calculations. You type
( + 1 1 )
into the top part of DrRacket, click RUN , and a result shows up in the bottom part: 2
That’s how simple programming is. You ask questions as if DrRacket were a child, and DrRacket computes for you. People often say the “computer does X for you” but in reality, a plain computer is pretty useless. It is software that computes. You can also ask DrRacket to process several requests at once:
( + 2 2 ) |
( * 3 3 ) |
( - 4 2 ) |
( / 6 2 ) |
After you click RUN , you see 4 9 2 3 in the bottom half of DrRacket, which are the expected results.
Terminology At this point, we slow down for a moment and introduce some terms:
-
The top-half of DrRacket is called the definitions area . In this area, you create the programs, which is called editing . As soon as you add a word or change something in the definitions area, the SAVE button shows up in the top-left corner. When you click SAVE for the first time, DrRacket asks you for the name of a file so that it can store your program for good. Once your definitions area is associated with a file, clicking SAVE ensures that the content of the definitions area is stored safely in the file.
-
Programs consist of expressions . You have seen expressions in mathematics. For now, an expression is either a plain number or something that starts with a left parenthesis “(” and ends in a matching right parenthesis “)”—which DrRacket rewards by shading the area between the pair of parentheses.
-
When you click RUN , DrRacket evaluates the expressions in the definitions area and shows their result in the interactions area . Then, DrRacket, your faithful servant, awaits your commands at the prompt . The appearance of the prompt signals that DrRacket is waiting for you to enter additional expressions, which it then evaluates like those in the definitions area:
Enter an expression at the prompt, hit the “return” or “enter” key on your keyboard, and watch how DrRacket responds with the result. You can do so as often as you wish:
> ( + 2 2 ) |
4
|
> (* 3 3 ) |
9
|
> ( - 4 2 ) |
2
|
> ( / 6 2 ) |
3
|
> ( sqr 3 ) |
9
|
> expt 2 3 ) |
8
|
> ( sin 0 ) |
0
|
> ( cos pi ) |
...