Fundamentals of Computer Science I: Media Computing (CS151.01 2008S)

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:

;;; 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)))))

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.

Supporting Multiple Alternatives with cond

When there are more than two alternatives, 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.

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 exp-0 exp-1 ... exp-n) behaves much like the following cond expression, except that the or version evaluates each expression once, rather than twice.

(cond
  (exp-0 exp-0)
  (exp-1 exp-1)
  ...
  (exp-n exp-n)
  (else #f))

Similarly, (and exp-0 exp1 ... expn) behaves much like the following cond expression.

(cond
  ((not exp-0) #f)
  ((not exp-1) #f)
  ...
  ((not exp-n) #f)
  (else exp-n))

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?)

;;; 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 selection-replace
                                (drawing-left drawing)
                                (drawing-top drawing)
                                (drawing-width drawing)
                                (drawing-height drawing))
       (image-fill! image))
      ((equal? (drawing-type drawing) 'ellipse)
       (context-set-fgcolor! (drawing-color drawing))
       (image-select-ellipse! image selection-replace
                              (drawing-left drawing)
                              (drawing-top drawing)
                              (drawing-width drawing)
                              (drawing-height drawing))
       (image-fill! image))
      (else
       (image-draw-line! image 0 0 (image-width image) (image-height image))))))

Reference

(if test consequent alternative)
Standard keyword. Evaluate test. If its value is truish (that is, anything but false), evaluate consequent and return its value. If the value of test is false (#f), evaluate and return alternative.
(cond (test1 consequents1) (test2 consequents2) ... (testn consequentsn) (else alternative))
Standard keyword. Evaluate each test in turn until one is truish. It then evaluates the corresponding sequence of consequent expressions and returns the value of the last consequent. If none of the tests is truish, evaluates the alternative and returns its value.
(and exp1 exp2 ... expn)
Standard keyword. Evaluate each expression in turn. If any of those values is false, return false. Otherwise, return the value of the last expression.
(or exp1 exp2 ... expn)
Standard keyword. Evaluate each expression in turn. If any of those values is true, return true. Otherwise, return the value of the last expression.

Creative Commons License

Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright (c) 2007-8 Janet Davis, Matthew Kluber, and Samuel A. Rebelsky. (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 license, visit http://creativecommons.org/licenses/by-nc/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.