Control Flow
Let Statement
A let statement can be used to define a function within the scope of another function.
For example, let's look at the following code:
When this function is called, it will first assign the product of the width and height to an area function, then call that area function to check if it's greater than 100, returning a boolean value.
This function body can also be written as width * height > 100
, but using a let statement can make the code somewhat more readable.
It can also be written in one line using a ->
symbol:
If Statement
An if statement can be used to return one of two different values depending on if a condition is true or false.
For example, let's look at the following code:
This will return a square when is_square
is true and a circle when is_square
is false.
It can also be written in one line using the ->
symbol:
To check for multiple conditions, you can chain if statements together like so:
In this example, the shape
function will return a square when n
is 1 or higher, a circle when n
is -1 or lower, and a triangle when n
is 0.
Match Statement
A match statement can be used to compare a value to multiple patterns and return a value when a pattern is matched.
For example, let's look at the following code:
This will return a square when n
is 0, a circle when n
is 1, a triangle when n
is 2, and default to an empty shape when n
is any other value.
It can also be written in one line using the ->
symbol:
You can also check for multiple patterns in a single case by separating the patterns with commas:
Loop
A loop can be used to generate a list of values of a defined amount.
For example, let's look at the following code:
This will return a list of squares with a length of n
. Say that we called this function with squares 3
. This would return the list [SQUARE, SQUARE, SQUARE]
.
It can also be written in one line using the ->
symbol:
This particular function wouldn't be very helpful, because all of the squares would be drawn on top of each other. One thing loops are useful for is generating a list of randomized shapes.
For example, we can create a list of randomly rotated squares like so:
For Loop
A for loop can be used to generate a list of values by iterating over an existing list or range.
For example, let's look at the following code:
This will iterate over the range 0..amount
, which is an exclusive range, meaning that if the amount is 3 the range will include [0, 1, 2]
. An inclusive range can be represented with 0..=amount
, which would include [0, 1, 2, 3]
.
Each value in the range is assigned to the i
function. Then, for each i
, it will add n
and return it.
Say that we called this function with add_to_range 1 5
. This will return the list [1, 2, 3, 4, 5]
, because it would iterate over the range 0 to 4 and add one to each value.
It can also be written in one line using the ->
symbol:
Last updated