Conditional Statements and Control Flow in Scheme

July 10, 2024

This post covers conditional statements such as if, cond, and case in Scheme. Learn how to control the flow of your program based on different conditions and make decisions using predicates.

if Statement

The if statement in Scheme is used to make decisions based on a condition. It has the following syntax:

(if <condition> <consequent> <alternative>)

If the condition is true, the consequent expression is evaluated, otherwise the alternative expression is evaluated.

cond Statement

The cond statement allows you to evaluate multiple expressions and choose the first one that evaluates to true. It has the following syntax:

(cond (<condition1> <expression1>) (<condition2> <expression2>) ... (else <default-expression>))

Each condition-expression pair is enclosed in parentheses. The else keyword is used to provide a default expression if none of the conditions are true.

case Statement

The case statement in Scheme is used for multi-way branching based on the value of an expression. It has the following syntax:

(case <key> ((<value1> <expression1>) (<value2> <expression2>) ... (else <default-expression>)))

The case statement matches the value of the key expression with the specified values and evaluates the corresponding expression. The else keyword is used for the default case.