If expressions allow one expression to conditionally be evaluated instead of another expression. They use the keywords if then else.
if "batman" > "superman" then "yay" else "boo";;
- : string = "boo"
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
if 0 then "yay" else "boo";;
File "[2]", line 1, characters 3-4:
1 | if 0 then "yay" else "boo";;
^
Error: This expression has type int but an expression was expected of type
bool
because it is in the condition of an if-statement
if true then "yay" else 1;;
File "[3]", line 1, characters 24-25:
1 | if true then "yay" else 1;;
^
Error: This expression has type int but an expression was expected of type
string
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.
if e1 then e2 else e3
e1 ==> true and e2 ==> v, then if e1 then e2 else e3 ==> ve1 ==> false and e3 ==> v, then if e1 then e2 else e3 ==> vif 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."