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.
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.
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
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
;;; Procedure: ;;; component-enhance ;;; Parameters: ;;; component, an integer ;;; Purpose: ;;; Compute an enhanced version of component. A large component gets ;;; larger. A small component gets smaller. ;;; Produces: ;;; new-component, an integer ;;; Preconditions: ;;; component is an integer between 0 and 255, inclusive ;;; Postconditions: ;;; If component > 127, then new-component is approximately 20% larger ;;; than component. ;;; If component < 128, then new-component is approximately 20% smaller ;;; than component. (define component-enhance (lambda (component) (if (> component 127) (min 255 (round (* 1.2 component))) (round (* 0.8 component)))))
of the form
test is always evaluated first. If its value is
#t (which means “yes” or “true”),
consequent is evaluated, and the
alternative (the expression following the
consequent) is ignored. On the other hand, if the value of the test
#f, then the consequent is ignored and the alternative
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.
It is also possible to write an if expression without the alternative.
Such an expression has the form
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
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 evaluating a
when expression, the Scheme
interpreter first evaluates the
test. If the
test holds, the interpreter evaluates each
expression in turn.
When there are more than two choices, it is often more convenient
to set them out using a
cond is a keyword. (Recall that keywords differ
from procedures in that the order of evaluation of the parameters may
cond keyword is followed by zero or
more lists-like expressions called
consequent-0) ... (
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
the consequent for that test is evaluated and its value is the value
of the whole cond expression.. Subsequent
clauses are completely ignored.
In other words, when Scheme encounters a
expression, it works its way through the
clauses, evaluating the test at the beginning of each one, until it
reaches a test that succeeds (one that does not
#f as its value). It then makes a ninety-degree turn
and evaluates the consequent in the selected
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
expression with a
cond clause in which the
else appears in place of a test. Scheme treats
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
For example, here is a
cond expression that
produces black, white, or grey based only on the red component of a
(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
(< (rgb-red c) 96). If the red component of
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
(> (rgb-red c) 160), which determines if the red
component is large. If it is, then we return the color white.
c has a red component that is neither small nor
large, then we proceed instead to the third
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.
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.
consequent-0-m) ... (else
In this case, when a test succeeds, each of the remaining subexpressions
(that is, consequents) in the same
is evaluated in turn, and the value of the last one becomes the value
of the entire
As you may have noted from our discussion of
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 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.
As we saw in the
reading on Boolean values, both
or provide a type of conditional behavior.
and evaluates each argument
in turn until it hits a value that is
#f and then
#f (or returns the last value if none return
or evaluates each
argument in turn until it finds one that is not
in which case it returns that value, or until it runs out of values,
in which case it returns
behaves much like the following
cond expression, except
or version evaluates each expression once,
rather than twice.
exp1) ... (
expn) (else #f))
behaves much like the following
exp0) #f) ((not
exp1) #f) ... ((not
expn) #f) (else
Most beginning programmers find the
much more understandable, but some advanced Scheme programmers use the
or forms because they
find them clearer. Certainly, the
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
drawing-type procedure to figure that out.
The two most important types are
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
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?)
;;; Procedure: ;;; drawing-render! ;;; Parameters: ;;; drawing, a drawing value ;;; image, an image id ;;; Purpose: ;;; Render drawing on the image. ;;; Produces: ;;; [Nothing; called for side effect] ;;; Preconditions: ;;; drawing can be rendered on image. ;;; Postconditions: ;;; drawing has been rendered on image. (define drawing-render! (lambda (drawing image) (cond ((equal? (drawing-type drawing) 'rectangle) (context-set-fgcolor! (drawing-color drawing)) (image-select-rectangle! image REPLACE (drawing-left drawing) (drawing-top drawing) (drawing-width drawing) (drawing-height drawing)) (image-fill-selection! image)) ((equal? (drawing-type drawing) 'ellipse) (context-set-fgcolor! (drawing-color drawing)) (image-select-ellipse! image REPLACE (drawing-left drawing) (drawing-top drawing) (drawing-width drawing) (drawing-height drawing)) (image-fill-selection! image)) (else (image-draw-line! image 0 0 (image-width image) (image-height image))))))
test. If its value is truish (that is, anything but false), evaluate
consequentand return its value. If the value of test is false (#f), evaluate and return
consequents2) ... (
test. If it holds, evaluate each expression in turn. Otherwise, do nothing.
Copyright (c) 2007-10 Janet Davis, Matthew Kluber, Samuel A. Rebelsky, and Jerod Weinman. (Selected materials copyright by John David Stone and Henry Walker and used by permission.)
This material is based upon work partially supported by the National Science Foundation under Grant No. CCLI-0633090. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.
This work is licensed under a Creative Commons
Attribution-NonCommercial 2.5 License. To view a copy of this
or send a letter to Creative Commons, 543 Howard Street, 5th Floor,
San Francisco, California, 94105, USA.