I was reading the most recent article on perl.com, and a code segment reminded me of something I see rather often in code that I don't like. Here's the code, Perl6ized:
... ; my $is_ok = 1; for 0..6 -> $t { if abs(@new[$t] - @new[$t+1]) > 3 { $is_ok = 0; last; } } if $is_ok { push @moves: [$i, $j]; } ...
What's wrong with:
for 0..6 -> $t { if abs(@new[$t] - @new[$t+1]) > 3 { push @moves: [$i, $j]; last; } }
I see this idiom a lot in code. You loop through some values on a condition, and do something only if the condition was never true. $is_ok is a control flow variable, something I like to minimize. Now, there are other ways to do this:
if (0..6 ==> grep -> $t { abs(@new[$t] - @new[$t+1]) }) { ... }
But one would say that's not the cleanest thing in the world.
and very unreadable, (even if that's heresy :-) )
Python pulled this idiom out in to the syntax (yay them), with C<else> on loops. The else block on a python loop executes only if you never broke out of the loop. That's a great idea.
So, in Perl's postmodern tradition, I think we should steal that idea. I'm a little uneasy about calling it C<else>, though. Maybe C<FINISH> would do, making the example:
for 0..6 -> $t {
if abs(@new[$t] - @new[$t+1]) > 3 {
last;
}
FINISH { push @moves: [$i, $j];
}
}
Violates least surprise, if the 'if' is true for '$t == 6' due to the ambiguity between 'last' on '$t==6' and falling out the bottom of the loop. Maybe you want FINISH_EARLY instead?
-- [EMAIL PROTECTED] [EMAIL PROTECTED]