Looping
JsLIGO currently supports iteration through loops, which we
understand as syntactic constructs where the state of a stopping
condition is mutated until it becomes true and the loop is
exited. There are two kinds of loops: for
loops and the more general
while
loops.
Here is how to compute the greatest common divisors of two natural
numbers by means of Euclid's algorithm and a while
loop:
Note the use of a conditional statement to swap x
and y
.
Conditional logic enables forking the control flow depending on the state, that is, the values available at a given point in the code. Put in a less technical manner, conditionals enable decision making.
A conditional statement is made of three parts:
- a condition, that is, a boolean expression;
- a statement evaluated if, and only if, the condition is true;
- a statement evaluated if, and only if, the condition is false.
The syntax uses the keyword if
to introduce the condition, a
statement or block of statements between {
and }
for the second
part, and the keyword else
introduces the last statement or block of
statements. The last part can be omitted, as in the example above.
Note: Currently JsLIGO does not support the keywords
break
&continue
in the context of loops.
By comparison, here is how to compute the greatest common divisors of two natural numbers by means of Euclid's algorithm using tail recursion (no loops):
Note: The conditional statements are complete: they both feature an
else
statement.
Finally, here is how to check if a string is a palindrome using a
for
loop:
Note: The
return
statement ("early exit") is not valid in loops.
for-of loops
JsLIGO for-of
loops can iterate through the contents of a
collection, that is, a list, a set or a map. This is done with a loop
of the form for (const <element var> of <collection var>) <block>
.
Here is an example where the integers in a list are summed up.
See the relevant sections on maps and sets for their loops.