If Else in Racket

Our first example demonstrates branching with if and else in Racket.

#lang racket

; Here's a basic example.
(if (= (remainder 7 2) 0)
    (displayln "7 is even")
    (displayln "7 is odd"))

; You can have an if statement without an else.
(when (= (remainder 8 4) 0)
  (displayln "8 is divisible by 4"))

; Logical operators like 'and' and 'or' are often useful in conditions.
(when (or (= (remainder 8 2) 0)
          (= (remainder 7 2) 0))
  (displayln "either 8 or 7 are even"))

; In Racket, we can use 'let' to bind variables before a conditional.
(let ([num 9])
  (cond
    [(< num 0) (displayln (format "~a is negative" num))]
    [(< num 10) (displayln (format "~a has 1 digit" num))]
    [else (displayln (format "~a has multiple digits" num))]))

To run the program, save it as if-else.rkt and use the racket command:

$ racket if-else.rkt
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Racket, you don’t need parentheses around conditions, but the entire if expression is enclosed in parentheses. The cond expression is used for multiple branches, similar to if-else chains in other languages.

Racket doesn’t have a direct equivalent to the ternary operator found in some languages, but you can use the if expression for similar functionality.

In Racket, the when special form is used for conditionals without an else clause, and unless can be used for the negative case. The cond form is particularly useful for multiple conditions, providing a clear and concise way to express complex branching logic.