Comprehension is More Than Syntax Sugar

While the previous section emphasized the ergonomic and simplifying qualities of Comprehensions, it should be explicitly stated that this construct is not just syntax sugar. Specifically, there is no other way in the language to directly initialize a List/Set/Map with size and elements determined dynamically at runtime without incurring an extra copy:

Fig 1:


var mutList: mut [string] = mut [];
for (x in [1, 3, 99, 2, 1]) {
  if (x <= 10) {
    lists::add(mutList, strings::repeated("*", x));
  }
}

# Claro is automatically coercing the copied list to be immutable.
var immutableList: [string] = copy(mutList);
print(immutableList);

Output:

[*, ***, **, *]

Using List Comprehension instead not only produces much simpler code, but will also allow you to drop the unnecessary copy:

Fig 2:


var immutableList = [strings::repeated("*", x) | x in [1, 3, 99, 2, 1] where x <= 10];
print(immutableList);

Output:

[*, ***, **, *]

Note: Read more about Claro's built-in copy(...) operator here (TODO(steving)).