If Else in Racket
Our first example demonstrates branching with if
and else
in Racket.
To run the program, save it as if-else.rkt
and use the racket
command:
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.