ZetCode

Scheme conditionals

last modified November 24, 2026 Guile 3.0

Scheme chooses between alternatives with a few special forms. if picks one of two expressions, cond tests a sequence of conditions, case compares a value with lists of constants, and when and unless run a group of expressions for their effect. All of them are expressions that return a value. The tests follow the truth rule from the booleans and equality article: only #f is false. The examples run with GNU Guile 3.0.7.

if without an alternative

The basics article used if with a test and two branches. The second branch, the alternative, may be left out. When the test is false, such an if returns an unspecified value, so the one-armed form is used for side effects. A branch is a single expression; begin groups several.

onearm.scm
(define (warn-if-low level)
  (if (< level 10)
      (begin
        (display "warning: level ")
        (display level)
        (newline))))

(warn-if-low 5)
(warn-if-low 50)

(write (if (> 3 2) 'yes))
(newline)
(write (if (< 3 2) 'yes))
(newline)

warn-if-low prints a message only when the level is below 10, and the call with 50 prints nothing. The begin is needed because the branch consists of three expressions. The last two lines show the values of a one-armed if: the symbol yes when the test is true, and an unspecified value, which Guile writes as #<unspecified>, when it is false. A program should not depend on that value.

$ guile onearm.scm
warning: level 5
yes
#<unspecified>

Nested if expressions

To choose among more than two outcomes, an if can be placed in the alternative of another one. The next program converts points to a grade from A to F this way.

nested.scm
(define (grade points)
  (if (>= points 90)
      'A
      (if (>= points 75)
          'B
          (if (>= points 60)
              'C
              (if (>= points 50)
                  'D
                  'F)))))

(display (list (grade 95) (grade 80) (grade 64) (grade 51) (grade 30)))
(newline)

Each test is reached only when all the earlier ones failed, so (>= points 75) means 75 to 89 points. The program works, but every level adds indentation and a closing parenthesis, and the structure of a simple chain of tests is hard to see. Five calls are collected with list to print the results on one line.

$ guile nested.scm
(A B C D F)

cond

cond is written for a chain of tests. It consists of clauses, each a test followed by expressions. The clauses are tried in order; the first clause whose test is true is selected, and the value of its last expression is the value of the cond. An else clause at the end catches all remaining cases.

grades.scm
(define (grade points)
  (cond ((>= points 90) 'A)
        ((>= points 75) 'B)
        ((>= points 60) 'C)
        ((>= points 50) 'D)
        (else 'F)))

(display (list (grade 95) (grade 80) (grade 64) (grade 51) (grade 30)))
(newline)

This is the grading procedure from the previous section rewritten with cond. The tests line up one below the other and the order of evaluation is the same: the first true test wins. The result is identical.

$ guile grades.scm
(A B C D F)

cond clauses

A cond clause may contain several expressions, which are evaluated in order, so it needs no begin. A clause may also consist of a test alone; its value is then the value of the test. When no clause is selected and there is no else, the result is unspecified.

clauses.scm
(define (check-stock item count)
  (cond ((= count 0)
         (display item)
         (display ": sold out")
         (newline)
         'reorder)
        ((< count 5)
         (display item)
         (display ": only ")
         (display count)
         (display " left")
         (newline)
         'low)
        (else 'ok)))

(write (check-stock "pens" 0))
(newline)
(write (check-stock "paper" 3))
(newline)
(write (check-stock "ink" 40))
(newline)

(write (cond ((string->number "12")) (else 0)))
(newline)
(write (cond ((> 1 2) 'never)))
(newline)

In check-stock, the first two clauses print a message and then return a symbol, the value of their last expression. The else clause returns ok without printing. The clause ((string->number "12")) has only a test, and because the test returns the number 12 rather than #f, the cond returns 12. The last cond has no true test and no else.

$ guile clauses.scm
pens: sold out
reorder
paper: only 3 left
low
ok
12
#<unspecified>

The => arrow

A clause can pass the value of its test to a procedure. It is written as the test, the symbol =>, and an expression that evaluates to a procedure of one argument. This is useful when the test computes something that the clause needs, as many Scheme procedures return either a useful value or #f.

arrow.scm
(define (describe-input text)
  (cond ((string->number text)
         => (lambda (n) (list 'number n 'doubled (* 2 n))))
        ((string=? text "")
         '(empty))
        (else
         (list 'word (string-length text) 'characters))))

(write (describe-input "21"))
(newline)
(write (describe-input "3/4"))
(newline)
(write (describe-input ""))
(newline)
(write (describe-input "oak"))
(newline)

string->number returns the parsed number or #f. When it succeeds, the arrow passes the number to the lambda, so the string is parsed only once. The fraction "3/4" is a valid number too. The other clauses handle the empty string and plain words.

$ guile arrow.scm
(number 21 doubled 42)
(number 3/4 doubled 3/2)
(empty)
(word 3 characters)

case

case evaluates one expression, the key, and compares it with lists of constants. Each clause starts with a list of data, which is not evaluated, and the first clause whose list contains the key is selected. The comparison uses eqv?, so case suits numbers, characters, symbols, and booleans.

dispatch.scm
(define (days-in-month month)
  (case month
    ((1 3 5 7 8 10 12) 31)
    ((4 6 9 11) 30)
    ((2) 28)
    (else 'invalid)))

(define (classify c)
  (case c
    ((#\a #\e #\i #\o #\u) 'vowel)
    ((#\space #\tab #\newline) 'blank)
    (else 'other)))

(display (list (days-in-month 1) (days-in-month 4)
               (days-in-month 2) (days-in-month 13)))
(newline)
(display (list (classify #\e) (classify #\space) (classify #\k)))
(newline)

days-in-month groups the months by length, and a clause list may hold as many values as needed; (2) is a list with one element. classify uses characters as keys. Both procedures have an else clause for values that appear in no list. Leap years are ignored here; the last section of the article handles them.

$ guile dispatch.scm
(31 30 28 invalid)
(vowel blank other)

case with symbols

Symbols are the most common keys, because they work well as names for a fixed set of states. Since case compares with eqv?, a key must be the same kind of value as the constants in the clauses.

symbols.scm
(define (traffic-action light)
  (case light
    ((green) "go")
    ((amber yellow) "prepare to stop")
    ((red) "stop")
    (else "light is out of order")))

(define (show light)
  (display light)
  (display ": ")
  (display (traffic-action light))
  (newline))

(show 'green)
(show 'yellow)
(show 'red)
(show 'blue)
(show "red")

The symbols amber and yellow share one clause. The symbol blue is not listed and falls to the else clause. The last call passes the string "red"; it looks like the symbol when displayed, but a string is not eqv? to a symbol, so it is not matched either. case cannot compare strings by content.

$ guile symbols.scm
green: go
yellow: prepare to stop
red: stop
blue: light is out of order
red: light is out of order

when and unless

when evaluates its body when the test is true, and unless when it is false. The body may contain any number of expressions. These forms state that the code runs only for its effect and has no alternative, so they read better than a one-armed if with begin.

whenunless.scm
(define (process-order quantity in-stock)
  (when (> quantity in-stock)
    (display "not enough stock for ")
    (display quantity)
    (display " items")
    (newline))
  (unless (> quantity in-stock)
    (display "shipping ")
    (display quantity)
    (display " items")
    (newline)
    (display "remaining stock: ")
    (display (- in-stock quantity))
    (newline)))

(process-order 3 10)
(process-order 12 10)

process-order prints a warning when the order is larger than the stock and ships it otherwise. The body of unless has six expressions and needs no grouping. When the test does not select the body, the result is unspecified, as with a one-armed if.

$ guile whenunless.scm
shipping 3 items
remaining stock: 7
not enough stock for 12 items

Naming a type with cond

The data types article named the type of a value with nine nested if expressions. With cond the same procedure becomes a flat list of predicate tests.

typeof.scm
(define (type-of value)
  (cond ((boolean? value) 'boolean)
        ((number? value) 'number)
        ((char? value) 'char)
        ((string? value) 'string)
        ((symbol? value) 'symbol)
        ((null? value) 'empty-list)
        ((pair? value) 'pair)
        ((vector? value) 'vector)
        ((procedure? value) 'procedure)
        (else 'other)))

(define (show value)
  (write value)
  (display " has type ")
  (display (type-of value))
  (newline))

(show #t)
(show 3/4)
(show "text")
(show '(1 2))
(show #(1 2))
(show type-of)

Each clause pairs a predicate with the symbol to return, and the else clause replaces the innermost alternative of the nested version. As before, no value satisfies two of the predicates, so the order of the clauses does not change the result. The output is shorter than in the data types article because fewer values are shown.

$ guile typeof.scm
#t has type boolean
3/4 has type number
"text" has type string
(1 2) has type pair
#(1 2) has type vector
#<procedure type-of (value)> has type procedure

Combining conditions

Conditions can be expressed with cond or with the boolean operators, and the choice is a matter of readability. A year is a leap year when it is divisible by 4, except for years divisible by 100, unless they are also divisible by 400. The program writes the rule both ways.

leap.scm
(define (leap-year? year)
  (cond ((= (remainder year 400) 0) #t)
        ((= (remainder year 100) 0) #f)
        (else (= (remainder year 4) 0))))

(define (leap-year-short? year)
  (or (= (remainder year 400) 0)
      (and (= (remainder year 4) 0)
           (not (= (remainder year 100) 0)))))

(define (days-in-february year)
  (if (leap-year? year) 29 28))

(define (report year)
  (display year)
  (display ": ")
  (display (days-in-february year))
  (display " days in February, ")
  (display (if (eq? (leap-year? year) (leap-year-short? year))
               "both versions agree"
               "versions differ"))
  (newline))

(report 2024)
(report 2025)
(report 1900)
(report 2000)

leap-year? checks the most specific rule first, so each clause needs only one test. leap-year-short? states the same rule as one boolean expression with or, and, and not. days-in-february uses if to select a number, and report uses another if inside the argument of display to confirm that the two versions agree. 1900 is not a leap year, while 2000 is.

$ guile leap.scm
2024: 29 days in February, both versions agree
2025: 28 days in February, both versions agree
1900: 28 days in February, both versions agree
2000: 29 days in February, both versions agree

Source

Simple conditional evaluation — GNU Guile Reference Manual

R7RS: the Revised7 Report on Scheme

In this article we have used if with and without an alternative, replaced nested if expressions with cond, used clauses with several expressions and the => arrow, dispatched on constants with case, and run code for its effect with when and unless. The booleans and equality article explains the tests, and the procedures article continues with the ways procedures take their arguments.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.