For Loops

For loops in Claro are closely analogous to Java's "enhanced for-loops". They enable you to easily iterate over the elements of a collection.

For Loop Over Lists

Fig 1:


for (e in [1, 2, 3, 4, 5]) {
    print(e);
}

Output:

1
2
3
4
5

For Loop Over Sets

Fig 2:


for (e in {1, 2, 3}) {
  print(e);
}

Output:

1
2
3

For Loop Over Maps

Iterating over the elements of a map of type {K: V} using the for-loop construct will yield a loop variable whose type is tuple<K, V>:

Fig 3:


for (e in {'a': 1, 'b': 2, 'c': 3}) {
  print("Key: {e[0]} - Val: {e[1]}");
}

Output:

Key: a - Val: 1
Key: b - Val: 2
Key: c - Val: 3

Note 1:

For loops over tuples are not currently supported as it's unclear what the appropriate behavior would be iterating over a collection of heterogeneous types. It's possible that in the future support may be added for a loop variable whose type is oneof<...all unique types in the tuple...> but there are no current plans for prioritizing this.

Note 2:

Possible use of an uninitialized variable is a compile-time error:

Fig 4:


random::create()
  |> random::nextNonNegativeBoundedInt(^, 10)
  |> var r = ^;
var l: mut [int] = mut [];
while (r-- > 0) {
  lists::add(l, r);
}

var s: int;
for (elem in l) {  # <-- `l` could be empty.
    s = elem;
}
print(s);

Compilation Errors:

for_EX4_example.claro:13: Variable <s> may not have been initialized!
print(s);
      ^
Warning! The following declared symbols are unused! [s]
2 Errors

Exiting a For Loop Early

You can exit a loop early by using the break keyword as below.

Fig 5:


for (e in [1, 2, 3, 4, 5]) {
    if (e == 3) {
      break;
    }
    print(e);
}

Output:

1
2

Skipping to the Next Iteration of the For Loop

You can also skip ahead to the loop's next iteration by using the 'continue' keyword as below.

Fig 6:


for (e in [1, 2, 3, 4, 5]) {
    if (e % 2 == 0) {
      continue;
    }
    print(e);
}

Output:

1
3
5