Conditional Evaluation in Scheme
Summary:
Many programs need to make choices. In this reading, we consider
Scheme's conditional expressions, expressions
that allow programs to behave differently in different situations.
We also consider how conditionals help us draw some simple shapes.
Introduction
When Scheme encounters a procedure call, it looks at all of the
subexpressions within the parentheses and evaluates each one.
Sometimes, however, the programmer wants Scheme to exercise more
discretion. Specifically, the programmer wants to select just one
subexpression for evaluation from two or more alternatives. In such
cases, one uses a conditional expression, an
expression that tests whether some condition is met and selects the
subexpression to evaluate on the basis of the outcome of that test.
For instance, suppose we want to increase a value by 20% if it
is greater than 127 and reduce it by 20% if it is less than 128.
(You may recall a similar problem from a recent laboratory exercise.)
While it is possible to write an interesting expression to do this
computation, many programmers would prefer something a bit clearer.
To write a procedure that like this, we benefit from a mechanism that
allows us to explicitly tell Scheme how to choose which expression
to evaluate. Such mechanisms are the primary subject of this reading.
If Expressions
The simplest conditional expression in Scheme is an
if expression. An if
expression typically has three components: a test, a consequent, and
an alternative. It selects one or the other of these expressions,
depending on the outcome of a test. The general form is
(if test consequent alternative)
We'll return to the particular details in a moment. For now, let's
consider the conditional we might write for the procedure to make a
component more extreme.
(if (> component 127) ; If the component is greater than 127
(* component 1.2) ; Increment it by 20%
(* component 0.8)) ; Otherwise, decrement it by 20%
To turn this expression into a procedure, we need
to add the define keyword, a name (such as
component-enhance), a lambda expression, and such.
We also want to give appropriate documentation and a bit of cleanup
to the results.
Here, then, is the complete definition of the
component-enhance procedure:
In an if-expression
of the form (if
test consequent
alternative), the
test is always evaluated first. If its value is
#t (which means yes
or true
),
then the consequent is evaluated, and the
alternative (the expression following the
consequent) is ignored. On the other hand, if the value of the test
is #f, then the consequent is ignored and the alternative
is evaluated.
Scheme accepts if-expressions in which the value of
the test is non-Boolean. However, all non-Boolean values are classified
as truish
and cause the evaluation of the consequent.
Dropping the Alternative
It is also possible to write an if expression without the alternative.
Such an expression has the form (if
test consequent).
In this case, the test is still evaluated first. If the test holds
(that is, has a value of #t or anything other than
#f), the consequent is evaluated and its value is returned.
If the test fails to hold (that is, has value #f), the
if expression has no value.
Scheme programmers tend to use the alternative-free if expression much
less frequently than they use the traditional form. In general, your
first inclination should be to provide both a consequent and an
alternative when you write a conditional. Some Scheme programmers
object to the alternative-free if expression enough that they discourage
its use. In fact, the primary version of PLT Scheme used in MediaScheme
will not permit you to write an if expression without an alternative.
Newer versions of Scheme include another kind of conditional, the
when expression, which provides an alternative
to the alternative-free if expression.
(when test body1 body2 ... bodyn)
When evaluating a when expression, the Scheme
interpreter first evaluates the test. If the
test holds, the interpreter evaluates each body
expression in turn.
Supporting Multiple Alternatives with cond
When there are more than two choices, it is often more convenient
to set them out using a cond
expression. Like if,
cond is a keyword. (Recall that keywords differ
from procedures in that the order of evaluation of the parameters may
differ.) The cond keyword is followed by zero or
more lists-like expressions called cond
clauses.
(cond
(test-0 consequent-0)
...
(test-n consequent-1)
(else alternate))
The first expression within a cond clause is a test,
similar to the test in an if expression. When the value
of such a test is found to be #f, the subexpression
that follows the test is ignored and Scheme proceeds to the test
at the beginning of the next cond clause. But when
a test is evaluated and the value turns out to be true, or even
truish
(that is, anything other than #f),
the consequent for that test is evaluated and its value is the value
of the whole cond expression.. Subsequent cond
clauses are completely ignored.
In other words, when Scheme encounters a cond
expression, it works its way through the cond
clauses, evaluating the test at the beginning of each one, until it
reaches a test that succeeds (one that does not
have #f as its value). It then makes a ninety-degree turn
and evaluates the consequent in the selected cond
clause, retaining the value of the consequent.
If all of the tests in a cond expression are found
to be false, the value of the cond expression is
unspecified (that is, it might be anything!). To prevent the surprising
results that can ensue when one computes with unspecified values,
good programmers customarily end every cond
expression with a cond clause in which the
keyword else appears in place of a test. Scheme treats
such a cond clause as if it had a test that
always succeeded. If it is reached, the subexpressions following
else are evaluated, and the value of the last one is the
value of the whole cond expression.
For example, here is a cond expression that
produces black, white, or grey based only on the red component of a
color, c.
(cond
((< (rgb-red c) 96)
color-black)
((> (rgb-red c) 160)
color-white)
(else
color-grey))
The expression has three cond clauses. In the first, the test
is (< (rgb-red c) 96). If the red component of c
happens to be the small,
the value of this first test is #t, so we evaluate
whatever comes after the test to find the value of the entire expression,
in this case, the color black.
If the red component of c is not small, then we proceed
instead to the second cond clause. Its test
is (> (rgb-red c) 160), which determines if the red
component is large. If it is, then we return the color white.
However, if c has a red component that is neither small nor
large, then we proceed instead to the third cond
clause. Since the keyword else appears in this
cond clause in place of a test, we take that as
an automatic success and evaluate color-grey, so that
that value of the whole cond expression in this
case is the color grey.
Multiple Consequents
Although we have written our conditionals with one consequent per
test (and we encourage you to do the same), it is, in fact, possible
to have multiple consequents per test.
(cond
(test-0 consequent-0-0 consequent-0-1 ... consequent-0-m)
...
(else alternate-0 alternate-1 ... alternate-a))
In this case, when a test succeeds, each of the remaining subexpressions
(that is, consequents) in the same cond clause
is evaluated in turn, and the value of the last one becomes the value
of the entire cond expression.
A Caution: Watch Your Parens!
As you may have noted from our discussion of cond,
cond expressions are another case in which
parentheses are used structurally. That is, many of the parentheses
do not surround an expression to evaluate. Rather, they serve only
to group things. In this case, the parentheses group the guard
and consequents for each cond clause.
When writing cond clauses, you should take the
time to verify that you've used the right number of parentheses.
Each clause has its own open and close parenthesis. Typically,
the test also has parentheses. Make sure to include both sets.
Expressing Conditional Computation with and and or
As we saw in the
reading on Boolean values, both and
and or provide a type of conditional behavior.
In particular, and evaluates each argument
in turn until it hits a value that is #f and then
returns #f (or returns the last value if none return
#f). Similarly, or evaluates each
argument in turn until it finds one that is not #f,
in which case it returns that value, or until it runs out of values,
in which case it returns #f.
That is, (or exp0
exp1 ... expn)
behaves much like the following cond expression, except
that the or version evaluates each expression once,
rather than twice.
(cond
(exp0 exp0)
(exp1 exp1)
...
(expn expn)
(else #f))
Similarly, (and exp0
exp1 ... expn)
behaves much like the following cond expression.
(cond
((not exp0) #f)
((not exp1) #f)
...
((not expn) #f)
(else expn))
Most beginning programmers find the cond versions
much more understandable, but some advanced Scheme programmers use the
and and or forms because they
find them clearer. Certainly, the cond equivalents
for both or and and are
quite repetitious.
Drawing with Conditionals
So, what does any of this have to do with images? Well, we've
already seen one thing: We can use conditionals in writing color
transformations. We also need conditionals to let us write procedures
for rendering drawing values on the screen. Why? Different types
of drawing values need to be rendered differently. For an important
example, ellipses should be rendered as ellipses, and rectangles should
be rendered as rectangles. How? Well, we'll generally want to figure
out what kind of drawing it is and then use GIMP commands to draw
it there. We might describe the algorithm in English as something like
If the drawing is a rectangle
select the appropriate region
set the foreground color
fill the rectangle
Otherwise, if the drawing is an ellipse
select the appropriate region
set the foreground color
fill the ellipse
Otherwise, we don't know what kind of drawing it is
Use some default behavior
First, we need to be able to find out the type of a drawing. We use
the drawing-type procedure to figure that out.
The two most important types are ellipse and
rectangle. (There are other types, but those are the
only ones we'll deal with right now.)
We also need to know how to get all of the components. These are
given by
drawing-left,
drawing-top,
drawing-width,
drawing-height, and
drawing-color. You can get a bit more information
on all of them on
the reference page.
Now, we're ready to put it all together. This procedure is among the
longest and most complex you've seen so far, in part because it accounts
for three different conditions.
(Can you think of any ways to make it simpler or more concise?)