One thing I like about Zig is that, while in general the language is minimal, it has a very rich vocabulary of control flow constructs (labeled block, break out of loop with value, for/else).
So, for example, expressing search in Zig is very natural:
const found = for(items) |item| {
if (predicate(item)) break item;
} else null;
what bugs me, however, is that I can’t quite find an equally compelling form for reductions, like finding a sum or a maximal element.
The most straightforward way to write it is of course something like this:
var max: u32 = 0;
for (items) |item| max = @max(max, item);
The problem here is that max remains mutable after the loop, which of course isn’t a big problem, but still feels somewhat unsatisfactory. You can do something like
var max_running: u32 = 0;
for ...
const max = max_running;
but then you have an extra variable in scope…
The “clean” way to write it would be:
const max = b: {
var max: u32 = 0;
for (items) |item| max = @max(max, item);
break b: max;
};
But then it reads too busy, with an extra indentation level, a block label and a break… Not really worth it, compared to the simple solution of making the max mutable.
Is there a nicer way to express this I am missing?