Scheme Programming/Conditionals

From Wikibooks, open books for an open world
< Scheme Programming
Jump to: navigation, search

This is a very important part of any program, as it can allow your program to make decisions, based on simple rules and the data it is given. Almost all useful Scheme programs make use of conditional expressions. Whether deciding if a number is even or odd, or if two strings are equivalent, conditionals litter most Scheme programs, and are a core part of all Turing complete languages.

In order to tackle conditionals, we must understand relational, equivalence and Boolean logic expressions

Relational and Equivalence Expressions[edit]

These determine how one value relates to another, is x larger than y? Is x the same as y? And so on and so forth.

(< a b)
#t if 'a' is strictly less than 'b', #f otherwise.
(<= a b)
#t if 'a' is less than or equal to 'b', #f otherwise.
(> a b)
#t if 'a' is strictly greater than 'b', #f otherwise.
(>= a b)
#t if 'a' is greater than or equal to 'b', #f otherwise.
(equal? a b)
#t if 'a' is exactly equal to 'b', #f otherwise.



Now we know how to compare variables with one another, we can start executing code based on this, using an if expression:

> (if (> 6 5) (+ x y) (- x y))

This code is very simple to understand; if the first expression is #t (i.e. true), then evaluate the second expression, otherwise evaluate the third.

In general, an if expression has the form:

(if (<Predicate>) (<Body for True>) (<Body for False>))

Using cond we can easily evaluate many expressions based on many predicates. It is a very useful construct.

(cond ((> x 0) x)
      ((= x 0) 0) 
      ((< x 0) -x))

The general form of the cond is as follows:

(cond (<p1> <e1>)
      (<pn> <en>)
      (else <exp>)

This demonstrates that a cond expression can have multiple 'clauses'. Each clause is composed of a 'predicate' (<p1> ... <pn>) and an expression to be evaluated if the predicate is true. The else clause at the end is entirely optional, though it is often used to help handle errors and such.