Switch in Racket

Here’s an example demonstrating the use of switch statements in Racket.

#lang racket

(require racket/datetime)

(define (main)
  ;; Here’s a basic switch equivalent using `case`.
  (let ((i 2))
    (printf "Write ~a as " i)
    (case i
      ((1) (printf "one\n"))
      ((2) (printf "two\n"))
      ((3) (printf "three\n"))))

  ;; You can use `cond` to handle multiple conditions.
  (let ((current-day (date-week-day (current-date))))
    (cond
      ((or (equal? current-day 'saturday)
           (equal? current-day 'sunday))
       (printf "It's the weekend\n"))
      (else
       (printf "It's a weekday\n"))))

  ;; `cond` without an expression is similar to if/else.
  (let ((t (current-seconds)))
    (cond
      [(< (seconds->date t 'iso8601) "12:00:00") (printf "It's before noon\n")]
      [else (printf "It's after noon\n")]))

  ;; Type checking using `cond`.
  (define (whatAmI i)
    (cond
      [(boolean? i) (printf "I'm a bool\n")]
      [(integer? i) (printf "I'm an int\n")]
      [else (printf "Don't know type ~a\n" (type i))]))
  (whatAmI #t)
  (whatAmI 1)
  (whatAmI "hey"))

(main)

To run the program, put the code in a file, for example, switch-example.rkt, and execute it using Racket.

$ racket switch-example.rkt
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

In this example, we demonstrate:

  • Using case for simple value-based branching.
  • Using cond for multiple conditions and ranges.
  • Checking the type of a variable using cond.

Now that we can manage conditional branching in Racket, let’s explore more features of the language.