Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Syntax and Evaluation

Conditionals: if, cond, case, when and unless

Make decisions in Racket and Scheme with if, cond, case, when and unless. Learn else clauses, the => form, predicates, and how to write clear nested conditions.

Every useful program makes decisions. Racket gives you a small set of conditional forms, each suited to a different shape of decision. In Lisp, a conditional is an expression: it produces a value, so you can pass it to a function or define a name with it. There is no separate "statement" world.

Examples run on the stand-in interpreter, which implements these forms with Racket's semantics.

if

(if test then-expr else-expr) evaluates test; if the result is anything except #f it evaluates and returns then-expr, otherwise else-expr. Both branches are required in Racket.

RACKET
(define (abs-value n)
  (if (< n 0) (- n) n))
(abs-value -7)   ; 7

Because if is an expression, you can use it anywhere a value goes:

RACKET
(string-append "You are " (if (>= 18 18) "an adult" "a minor"))
if as an expression

cond

When you have more than two cases, nested ifs become hard to read. cond tests clauses in order and returns the result of the first clause whose test is true. else is a catch-all that goes last.

RACKET
(define (grade score)
  (cond [(>= score 90) "A"]
        [(>= score 80) "B"]
        [(>= score 70) "C"]
        [else "F"]))

Clause order matters: (grade 95) matches the first test and stops. Each clause is [test result-expr ...]; if you give several result expressions, the last one is the value.

Grading with cond

A cond with no matching clause and no else returns void, which usually hides a bug. Add else unless you truly want nothing.

Clauses that return the test value

A clause with only a test returns the test's value if it is true. This works well with assoc:

RACKET
(cond [(assoc 'b '((a 1) (b 2))) => cadr]   ; 2
      [else 'missing])

The => arrow passes the test's value to a function (cadr here). It avoids computing the lookup twice.

case

case compares one value against several constants, with equal?. It is the tidy choice when you dispatch on a symbol or number:

RACKET
(define (day-type day)
  (case day
    [(sat sun) "weekend"]
    [(mon tue wed thu fri) "weekday"]
    [else "unknown"]))

Each clause lists the possible values in parentheses. The constants are not evaluated, so no quote is needed.

Dispatch with case

when and unless

Use when for one-armed conditions with side effects. It evaluates its body only if the test is true; unless does the opposite. Neither has an else branch, and both allow several body expressions.

RACKET
(when (> 3 2)
  (displayln "three is bigger")
  (displayln "done"))

(unless (> 3 5)
  (displayln "three is not bigger than five"))

Do not use when when you need a value in both cases; use if for that.

when and unless

and, or and not as conditions

and and or short-circuit and return values, so they can replace small ifs:

RACKET
(define (safe-first lst)
  (and (pair? lst) (car lst)))   ; #f for an empty list
(safe-first '())        ; #f
(safe-first '(7 8))     ; 7

Use them to combine tests: (and (> n 0) (< n 10)), (or (zero? n) (even? n)).

Choosing the right form

Situation Form
Two outcomes, a value either way if
Several ordered tests cond
One value against constants case
Side effects only when true when / unless
Combine boolean tests and, or, not

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a cond with no matching clause and no else return?

    cond returns void when no clause matches, which can hide bugs; add an else clause.
  2. 2. Which form fits dispatching on a symbol such as 'sat or 'wed?

    case compares one value with lists of constants using equal?.
  3. 3. What does (when #f (displayln "x")) do?

    when evaluates its body only if the test is true; otherwise it does nothing (returns void).
  4. 4. In a cond clause [(assoc 'b table) => cadr], what does => do?

    => calls the function on the value of the test, avoiding a second lookup.

Summary

  • Conditionals are expressions that produce values.
  • if for two branches; cond for several ordered tests (end with else); case for constants; when/unless for side effects.
  • Only #f is false, so and/or can return useful values.
  • Clause order matters in cond.

Next: Pairs and Lists