Loops
Introduction
Fuzion has powerful syntactic sugar for expressing loops.
To get an impression where we want to end up, the following example shows a loop that uses all of the available mechanics of loops in Fuzion (in
, while
, do
, until
, else
).
But first let's start simple and then work our way to more and more advanced loops.
Simple counting loops
This loop counts to 10 using a loop index variable:
The index field i
is initially set to 1
. After
each loop iteration, it will be set to the previous value plus one
i + 1
. The loop body prints the value of this index field
using say i
, and this body is executed repeatedly as long
as i <= 10
holds.
Even though it appears as if the index field i
is assigned a
new value during each loop iteration, the code does not mutate fields. Each
loop iteration creates a new instance of i
which is not
mutated.
Not mutating the index field has an enormous advantages: The field is an immutable field within the loop body, which allows for compiler optimizations and for cheap accesses within closures, even accesses from other threads are automatically safe.
Endless loop
The loop termination condition that so far was given in the while
part can be omitted to create an endless loop, as shown in the next example:
An endless loop is typically not very useful, the main exception being the control loop in a task that is supposed to continue forever.
However, as we will see next, iterating loops that operate over a finite stream of elements do not need an explicit termination condition, which will be shown in the following examples.
Iterating loops
Using a simple iterating loop enables us to further simplify the code of the previously presented counting loop by iterating over an interval:
What happens here is logically different from the previous loops: The expression
1..10
calls the feature infix ..
on the integer constant
1
with the argument 10
. This feature defines an interval from
the value it is called on to the value passed as an argument. So, in this case,
this defines an interval from 1 to 10, inclusive.
An interval is a List, which means that it can be used to define a loop
index field using in
.
Steps
The ability to loop over arbitrary streams of indices enables as well to loop
over integers using a step size larger than 1. Here is an example that prints
only even numbers by using a step of 2
:
This loop is essentially the same as the previous loop, only that the interval
that the loop iterates over now was created using a step size, which is done
using the operator infix :
on an integer interval.