If and Cond


Purpose

"If" is a function used to make a decision which of two actions should be taken. "Cond" is useful for deciding between more than two actions.

Usage

"If" takes two or three arguments. The first argument is called the "test". It can be any expression, but it should return a Boolean, i.e. "true" or "false".

If the test evaluates to true, the second argument will be evaluated. If the test evaluates to false, and a third (or "else") argument is present, it will be evaluated.

The "Cond" function is a bit more complicated. It takes any number of arguments. Each argument should be a list containing two elements. The first element in each list is a test, and the second can be any expression. Cond runs through the pair in order, evaluating each test until it finds one that returns true. At that point "cond" evaluates and returns the expression associated with the winning test.

Examples

A simple test:
  ox --> (if (> 2 1) 'yes 'no)
  yes
  ox --> (if (< 2 1) 'yes 'no)
  no
A "cond" example:
  ox --> (define animal 'cow)
  cow
  ox --> (cond ((eq? animal 'pig) 'oink)
               ((eq? animal 'cat) 'meow)
               ((eq? animal 'cow) 'moo)
               (else 'huh?))
  moo
Notice cond can have an "else" test which always will evaluate to true if all of the other tests fail.

Also notice cond can be used to select from a general list of choices. Here we will randomly select a shape:

  ox --> (define pick (ceiling (* (rand) 4)))
  2
  ox --> (cond ((= pick 1) (sphere))
               ((= pick 2) (cone))
               ((= pick 3) (box))
               ((= pick 4) (cylinder)))
  #f

Since pick was assigned 2, a cone would have been created.

Return to Scheme Introduction


mrl