16 If Expressions

If expressions allow one expression to conditionally be evaluated instead of another expression. They use the keywords if then else.

There are a few things at play here. The syntax is

if <guard> then <expression> else <expression>.

The guard must be a boolean, and both expressions must have the same type

These both fail because of incorrect types

The if expression is very similar to the ternary operator (? :) in other languages.


Now let's look at if expressions on paper.

Syntax

if e1 then e2 else e3

Evaluation

Type checking

if e1 : bool and e2 : t and e3 : t, then if e1 then e2 else e3 : t

It's worth noting that "==>" means "evaluates to" and ":" means "has type."