foreach can be the answer

C# foreach loop is undoubtedly elegant, however in daily use it is not efficient or versatile — I don’t envy the developers using the languages which dropped indexed for loop without solid substitution. When you need an index — usually you have to zip your collection with a range. Testing first or last element — a bit less common scenario — you need to add an extra scope with appropriate variables by hand. And adding nested continuation loop… — this is why I am glad C# still supports C-loop.

In Skila though, I am close to cover all the cases in a right way and have good reason not to introduce the old way of iterating. The performance is intact and you have concise syntax, starting from the basic form:

for elem in collection do
  ...
end

With just a control label (for any kind of loop — for, while and repeat-until) you can solve the common tasks:

loop: for elem in collection do
  stdOut.writeLine(loop.isLast); // `for` only
  stdOut.writeLine(loop.isFirst);
  stdOut.writeLine(loop.index);
  break loop; // here label is optional
end

All three “members” are just plain variables — when not used by the user, they are scrapped from the code, when used — they don’t leak. Nested loops are less of the rush (besides, they require more internal rewiring) so I’ll add them sometime in the future.

Advertisement
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: