Conditionals in Scheme

Chapter: Conditionals in Scheme

Just as in BASIC, C, Pascal, and most other programming languages, Scheme has a conditional expression. It is the keyword cond. Here is an example (try it out):

(cond 
  [(equal? 'birthday 'party) 'whoopee]  
  [#t 'boooooring]) 

cond works by searching through its arguments in order. It finds the first argument whose first element returns #t when evaluated, and then evaluates and returns the second element of that argument. It does not go on to evaluate the rest of its arguments.

Make sure that the last argument to every cond statement will always accept anything. This is important for avoiding infinite loops. One possible syntax for doing this is [#t < S-expression>], since #t always evaluates to #t. The Little Schemer always uses else instead of #t in this context. Either of these is perfectly acceptable to Scheme, but the latter can make your code easier to read.

So, in the above example, cond asks if (equal? 'birthday 'party) returns #t when evaluated. Since 'birthday and party are not equal, this returns #f, and cond goes on to check the next argument. Since #t returns #t, cond immediately returns 'boooooring.

Try this one too:

(cond 
  [(equal? 'birthday 'party) 'whoopee]  
  [(equal? 'cake 'cake) 'have-a-piece]
  [else 'boooooring])

(Note that in this sample, we have used the syntax from The Little Schemer for the final condition; again, it's your choice.) Just as in the above example, cond checks the first argument, finds that 'birthday does not equal 'party and goes on to the next argument. Here, 'cake does equal 'cake, so Scheme immediately returns 'have-a-piece. (It does not then go on to return 'boooooring, since it already found a case that was true).

By the way, the square brackets [ and ] are treated exactly the same as the parentheses ( and ). Sometimes it is helpful to use both types, in order to more easily match parentheses with each other.

Here are some example Scheme expressions. See if you can tell what their results will be before you type them in and test them.

(define apple 'delicious) 
(cond 
  [(equal? apple 'baseball) 'wrong]
  [(equal? apple 'delicious) 'right]
  [#t 'not-sure])

(define (weird x y z) 
    (+ x (* y (* z z))))
(weird 2 (* 6 4) 8)

We have one final exercise for you, a more substantial function which will actually be useful (!) and which will allow you to comment on today's lab. By the way, any comments you include will have no effect on your grade, so be sure to let us know what you think!


Exercise 5: A multipurpose function

In addition to putting your name at the top of your lab, write a one-argument function which does the following:

By the way, the easiest way to return your comments is to make them into a string by surrounding them with double quotes. For example, try typing "This is a string." at a Scheme prompt.



rms@cs.oberlin.edu