Conditional Expressions
if then else
if ... then ... else ... statements are designed to efficiently route program flow/functionality, via boolean logic, to one of two paths. These are generally decided by logical and numeric comparisons.
Examine the following block of code:
if a <= b
then True
else False
If the value of 'a' is less than or equal to 'b', the entire clause will return True. Otherwise, the clause will return False. This can be used to control the behavior of a function under variable situations.
match with
match ... with ... statements are designed to efficiently route program flow/functionality to one of many paths. These are typically used for handling more complex cases than if ... then ... else ... statements.
Examine the following code:
match x with
True -> 1,
"Hello" -> 2,
Int y -> y,
_ -> 0 (* Default Case *)
This match statement filters x into one of three integer values. Through the magic of arbitrary typing, x can be any type that provides a constructor for Booleans (True), Strings ("Hello"), and Integers (Int y). The result of a match case is constrained to a single type or typeclass; in this example, it resulted in an integer.
For a more practical example, see this function that sorts a color variable into the correct RGB (Red/Green/Blue) unit vector:
match color
with
Red -> RGB 255 0 0,
Green -> RGB 0 255 0,
Blue -> RGB 0 0 255,
_ -> RGB 0 0 0 (* Default Case *)
is
... is ... statements are quickhand type/constructor equivalence checkers. If the left-hand-side variable matches the right-hand-side type/constructor, the entire statement returns True, otherwise it returns False.
For the next examples, assume 'b' is a constant of type color, and constructor Blue.
The examples would both return 1.
if b is color
then 1
else 0
if b is Blue
then 1
else 0
Probing for Type Definitions
is can be extended to check for the existance of a type definition by using the following syntax:
if type color is null
then 0
else 1
If there is a color
defined as a type, the above clause will return 1
. Otherwise, it has not been defined, so the funtion will return 0
.
This functionality can be helpful in developing forwards/backwards-compatible code, when a type may not be defined yet.
The type ... is null
expression can be used at any time to return a boolean value (True if type is undefined).
When used with if
, it has special rules that allow developers to attempt to access elements that may have not been declared.
Right now, only one structure is supported (the one used in the previous example):
let test_color c =
if type color is null
then 0 (* Normal Access Rules *)
else c.r_value (* Does not check if 'r_value' exists at compile time *)
If color
is defined as a type and r_value
doesn't exist, a run-time error is thrown.