Conditionals

Conditionals

Robbert Haarman

2010-12-11


Introduction

Frequently, your program has to perform different actions depending on some value. The conditionals if and cond can be used to control this.


If

The simplest conditional in Scheme is if. In its simplest form, it takes a test and an expression as arguments. The expression is evaluated and the value returned if the test passes. If the test doesn't pass, if returns an undefined value. Another incarnation of if takes an additional expression as an argument, which is evaluated if the test is not passed. Below are some examples of each form.

; Display "Nothing happens." in response to the magic word
(if (string=? (read-line) "xyzzy") (display "Nothing happens."))

; Ask user if he wants to quit
(display "Really quit? (y/n) ")
(if (char-ci=? #\y (read-char))
	(exit)
	(display "Thanks for staying!"))

(if (= 0 1)
	(display "Can't happen!")
	(display "All is well"))

Cond

A more flexible, but also more complicated conditional is cond. An example follows:

(display "Input two numbers: ")
(let ((a (read)) (b (read)))
	(display
		(cond
			((= a b) "The numbers are equal")
			((> a b) "The first number is greater than the second")
			((< a b) "The first number is lower than the second"))))
(newline)

cond tries the alternatives in the order listed until the test for one of them passes. It then evaluates the expressions after that test. As always, the value of the last evaluated expression is returned. The alternative which has else for a test is chosen if none of the others match.


Case

The case construct can be used to take different actions depending on the value of an expression. It looks like cond, but takes an expression as its first argument, and instead of conditions, it takes lists of values to match against. An example:

(display "Would you like (1) ham, (2) cheese, (3) ham and cheese, (4) neither? ")
(case (read)
	((1)
		(display "Cutting ham...")
		(display "done"))
	((2 3)
		(display "Sorry, we're out of cheese"))
	((4)
		(display "Have a nice day, then"))
	(else
		(display "Invalid input!")))
(newline)
Valid XHTML 1.1! Valid CSS! Viewable with Any Browser