Loops
Iterating with for
Nanyx uses the for keyword to iterate. The iterable comes first, which keeps loops readable and supports pattern matching on the loop variable.
Basic loops
for 1..5 -> print("Hello")
for 1..5 | i -> print("Hello times {i}")
Pattern matching in loops
for 1..5 | { < 5 } -> println("Ready...")
| _ -> println("Go!")
Looping collections
def data = [1, 2, 3]
for data | item -> println(item)
Enumerating with indexes
Zip a collection with a range to keep a counter:
def data = ["one", "two", "three"]
for data, 0.. | item, i ->
print("Item number {i} is {item}")
Dictionaries
When iterating a map or dictionary, the loop variable is a record of the key and value:
def dict = ["one" => "uno", "two" => "dos"]
for dict | key, value -> print("{key} => {value}")
Ignoring loop variables
Use _ to ignore unused variables:
for dict | _, value ->
print("Only care about {value}")
While loops
for iterates over a collection that already exists. When the number of iterations depends on state that changes as the loop runs, use while, which repeats its body for as long as the condition is true:
memory {
def remaining = mut 3
while remaining > 0 ->
println("{remaining}...")
remaining := remaining - 1
}
Because the condition has to change for the loop to end, while is almost always used together with the $Memory context. It is the one low-level loop in the language, and exists so that locally mutable algorithms can be written inside an otherwise immutable interface.