# Conditional Evaluation in Scheme

This reading is also available in PDF.

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.

Contents:

## 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 this 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 (`enhance-component`), a lambda expression, and such. We also want to give appropriate documentation and a bit of cleanup to the results.

Here is the complete definition of the `enhance-component` procedure:

```;;; Procedure:
;;;   enhance-component
;;; 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 enhance-component
(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 s 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) (rgb.new 0 0 0))
((> (rgb.red c) 160) (rgb.new 255 255 255))
(else (rgb.new 127 127 127)))
```

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, 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 `(rgb.new 128 128 128)`, 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 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` for `and` is quite repetitious.

## Drawing with Conditionals

So, what does any of this have to do with drawing? Well, we've already seen one thing: We can use conditionals in writing color transformations. However, there's something much more fun that we can do with conditionals: We can use conditionals to draw simple shapes. How? We can use `region.compute-pixels!` and draw one color if the pixel falls within the shape and another if the pixel falls outside of the shape.

Here are a few conditionals that draw particular images. See if you can figure out what each one draws.

```(define c0 (rgb.new 255 255 255))
(define c1 (rgb.new 255 0 255))
(define c2 (rgb.new 255 0 0))
(define c3 (rgb.new 0 255 255))
(define square (lambda (x) (* x x)))

(region.compute-pixels! canvas 0 0 199 199
(lambda (pos)
(if (< (position.row pos) (- 100 (position.col pos))) c1 c0)))

(region.compute-pixels! canvas 0 0 199 199
(lambda (pos)
(if (< (position.row pos) (+ -75 (position.col pos))) c2 c0)))

(region.compute-pixels! canvas 0 0 199 199
(lambda (pos)
(if (>= (square 50)
(+ (square (- (position.col pos) 20))
(square (- (position.row pos) 60))))
c3 c0)))
```

We will return to these drawings, and others, in the corresponding laboratory.

### Drawing Multiple Shapes

Of course, each call to `region.compute-pixels!` will completely overwrite the previous drawing. What if we want to draw multiple shapes? There are a few possibilities: The most obvious is that we can put the different commands into a `cond`.

```(region.compute-pixels! canvas 0 0 199 199
(lambda (pos)
(cond
((>= (square 50)
(+ (square (- (position.col pos) 20))
(square (- (position.row pos) 60))))
c3)
((< (position.row pos) (+ -75 (position.col pos))) c2)
((< (position.row pos) (- 100 (position.col pos))) c1)
(else c0))))
```

That works fairly well, even though it's a bit inconvenient to write. But what if we want to draw something on top of an existing image. In that case, we can take advantage of a special feature of `region.compute-pixels!` - if the color is the special value `transparent`, then `region.compute-pixels!` does not modify the underlying pixel. (We simply mention this capability here; you will take advantage of it in the lab.)

## History

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Mon Dec 3 09:53:29 2007.
The source to the document was last modified on Wed Sep 19 10:37:39 2007.
This document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2007F/Readings/conditionals-reading.html`.

You may wish to validate this document's HTML ; ; Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright © 2007 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.