Thread overview | ||||||
---|---|---|---|---|---|---|
|
April 13, 2011 Else clauses for loops | ||||
---|---|---|---|---|
| ||||
Hi! A feature I use surprisingly often in Python is the else clause on loops. Is there something similar in D? Basically, the idea is that your loop is "looking for something" (or some condition), and that you'll break out of it if you find what you're looking for. If no break occurs, the else clause is executed. It makes for quite clean code in many cases, IMO. The alternative can be a flag variable, I guess, or a goto-statement (to right after the "else" bit) instead of a break. Or put it in a function, and use a return instead of a break ... or use scope() somehow, perhaps. I see that the feature has been requested a few years ago [1], so there might not be that much demand for this sort of thing. Is there perhaps a D idiom here already? [1] http://d.puremagic.com/issues/show_bug.cgi?id=2304 -- Magnus Lie Hetland http://hetland.org |
April 13, 2011 Re: Else clauses for loops | ||||
---|---|---|---|---|
| ||||
Posted in reply to Magnus Lie Hetland | You could wrap the loop in an if clause: if (condition) while (true) { // ... } else { // ... } |
April 13, 2011 Re: Else clauses for loops | ||||
---|---|---|---|---|
| ||||
Posted in reply to Bernard Helyer | Bernard Helyer:
> You could wrap the loop in an if clause:
>
> if (condition) while (true) {
> // ...
> } else {
> // ...
> }
This is the semantics of the else clause of Python for (and while) loops:
bool broken = false;
for (...) {
if (...) {
broken = true;
break;
}
}
if (!broken) {
...
}
I agree with BCS in the bug 2304, I'd like something more semantically descriptive instead of just an "else". It's handy, I use it now and then in Python, but I am able to live without it in D.
Bye,
bearophile
|
April 14, 2011 Re: Else clauses for loops | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | On 04/13/2011 06:48 PM, bearophile wrote: > Bernard Helyer: > >> You could wrap the loop in an if clause: >> >> if (condition) while (true) { >> // ... >> } else { >> // ... >> } > > This is the semantics of the else clause of Python for (and while) loops: > > bool broken = false; > for (...) { > if (...) { > broken = true; > break; > } > } > if (!broken) { > ... > } > > I agree with BCS in the bug 2304, I'd like something more semantically descriptive instead of just an "else". True. Python tends to overload its keywords, which leads to weird expression. Also weird, again using "then": try: n = 1 + 1 except Exception, e: print ("*error*") else: print (n) actually means try: n = 1 + 1 then: print (n) except Exception, e: print ("*error*") Denis -- _________________ vita es estrany spir.wikidot.com |
Copyright © 1999-2021 by the D Language Foundation