Next: Designing Conditional Programs -
Up: Conditional Expressions and Programs
Previous: Programs that Test Conditions-
A cond expression must contain a sequence of
condition lines, where each line has exactly two parts:
(cond
[condition1 answer1]
[condition2 answer2]
...)
(We're using square brackets to surround condition-answer pairs. You
can use round parentheses if you prefer.) When a poorly-formed
cond expression is typed into DrScheme, DrScheme highlights
the incorrect part of the expression as a syntax error. If an
individual condition line is highlighted, then only that line is
incorrect. If multiple lines are highlighted, then the parentheses
are not balanced in an individual line (so DrScheme thinks that
multiple lines are a single line).
Just like an expression in a definition, no extra parentheses can be
added around the condition or answer expressions in a
cond-line. Parentheses cannot be placed around
else.
Beyond the Shape Rules
The rules concerning the shape of a cond expression do not
specify the kind of condition expressions that are allowed.
In fact, a condition expression must have a Boolean value. For
example, according to the shape rules for forming a cond
expression, the following is a legal expression:
(cond
[1 2])
If you enter this expression in DrScheme, DrScheme tentatively accepts
the expression, but then checks whether the condition 1 is
true or false. It is neither, so DrScheme highlights the
1 and prints an error message. This is a run-time error.
The following is another legal expression according to the shape
rules:
(cond
[true 5]
[1 2])
In this case, DrScheme evaluates the expression and returns
5. Although 1 would be an illegal condition value
if the second condition is ever tested, DrScheme never tests it since
the first condition is always true.
When a cond expression is evaluated, at least one of the
conditions must be true. If no condition is true,
then DrScheme prints the run-time error ``no matching cond case.''
For example, the following expression generates the ``no matching
cond clause'' error, since there is only one condition and it is
false:
(cond
[false 0])
A cond expression with an else clause never
generates the ``no matching case'' error because the else
clause always matches.
Automatic Parenthesis Correction
When you type an close parenthesis ) where an open bracket
[ needs to be closed, DrScheme automtically changes
) to ] to close the bracket. For example, typing
) after
(define (positive? n)
(cond
[(> n 0) true
produces ], instead of ). Similarly, ] may
be automatically converted to ). Automatic parenthesis
correction is handy, but if it bothers you, turn it off via the
Edit|Preferences menu item.
Next: Designing Conditional Programs -
Up: Conditional Expressions and Programs
Previous: Programs that Test Conditions-
PLT