# Class 08: Conditionals

Reading: Boolean values. Reading: Conditionals. Back to Procedure Definitions. On to Conditionals Lab.

Held Friday, February 2, 2001

Summary

Today we begin to learn how to tell Scheme to make decisions. The procedures used to make decisions are called conditionals.

Due

Notes

Overview

• A problem: Turning numbers into letters.
• In English
• In conditional-less Scheme
• Making life easier: Conditionals

## A Problem

• Suppose that for fairness's sake, I'd like a program that converts numeric grades to letter grades.
• We'll look at two related grading schemes.
• 94-100: A, 90-93: B, 87-89: B+, 84-86: B, ...
• 10:A+ 9:A, 8:A-, 7:B+, 6:B, 5:B-, 4:C+ 3:C 2:C- 1:D 0:F
• How might you explain to someone how to turn a number into a grade?
• In either schema, can you write a procedure that turns a number into a grade, using only the Scheme you already know?

## First Solution: Use `if`

• As you may have noted from your narrative, we are often tempted to describe the procedure in terms of the word if. For example, if the grade is at least 94, then give the student an A, otherwise, if the grade is between 90 and 93, ...
• In Scheme, you can write such expressions as
```(if condition
success-expression
failure-expression)
```
• Note that `if` does not behave according to Marie's evaluation pattern (in which all the arguments to a procedure are computed before the procedure is applied).
• In particular, only one of the success-expression and failure-expression is computed.
• Given the Scheme that you know right now, the only effect is on efficiency.
• Later, you'll see that this decision affects other things, too.
• For example
```(if (>= grade 94) 'A 'F)
```
• We can nest these conditions.
```(if (>= grade 94)
'A
'Aminus
...)))
```

## Another Solution

• As you may have noticed, the code is somewhat hard to read (and awfully indented). Another alternative is to use Scheme's `cond`, which more closely resembles a table.
• Here's what a `cond` expression looks like
```(cond
((condition1) exp1)
((condition2) exp2)
((condition3) exp3)
...
(else default-exp))
```
• In this case, the conditions are evaluted one-by-one until one holds true. The value of the corresponding expression is the then returned.
• For our problem, this format seems particularly appropriate.
```(cond
...)
```

## History

Friday, 12 January 2001

• Created generic outline format for class.
• Amazingly enough, for this outline (at least) my course set up tool copied over the notes from the previous semester and reformatted them apropriately. You can find the original of the copied stuff at ' --> (that is, outline 9 of CSC151 2001).

Thursday, 1 February 2001

• Updated minor details.
• Added history note that the body was filled in automatically.
This page may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2001S/outline.08.html`.