The question here is "what's your favorite non-C-like flow control statement/construct that you've seen in a programming language" but I'm gonna start with a little preamble.
I'm very familiar with C-style flow control:
if (condition)
{ thing; }
else
{ otherThing; }
// And, thanks to C++17:
if (auto v= initializer(); condition)
{ thing(v); }
else
{ otherThing(v); }for (int i = 0; i < 5; i++)
{ thing(); }for (var e : elements)
{ thing(e); }while (condition)
{ thing(); }(plus, ya know, do/while and goto)
I've seen a few others, like Rust's loop (basically a while(true)):
loop
{
thing();
if (something)
{ break; }
}and Swift's ranges, which are nice:
for i in 0..<4
{ thing(i); }What I'm wondering is: what are your favorite bits of flow control logic (loops, jumps, conditionals, etc) that don't show up in C or C++? Are there loop forms that you think are truly elegant? Is there a switch-like construct that doesn't suck like C's switch statement does?
choosing the chaotic option and offering up for-else
for num in range(10):
print(x)
else:
print("I only go off if loop completed with no break statement")I love Swift's guard:
guard let index,
index >= 0 else {
throw Issues.noIndexProvided
}If you don't use Swift, the else block must exit the current scope (with a return, throw, break or continue), so subsequent statements will always see any variables captured/deconstructured by the guard. In that way, you can signal an early break or return very prominently without silly stuff like 'no early returns, so enjoy your pyramid of if indents'.
Factor has probabilistic combinators ifp, whenp, unlessp, and casep that take a probability for each function or case.
The following [form] will output 1 with 0.2 probability, 2 with 0.3 probability and 3 with 0.5 probability
USING: combinators.random prettyprint ;
{
{ 0.2 [ 1 ] }
{ 0.3 [ 2 ] }
{ 0.5 [ 3 ] }
} casep .
