www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Else clauses for loops

reply Magnus Lie Hetland <magnus hetland.org> writes:
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
Apr 13 2011
parent reply Bernard Helyer <b.helyer gmail.com> writes:
You could wrap the loop in an if clause:

    if (condition) while (true) {
        // ...
    } else {
        // ...
    }
Apr 13 2011
parent reply bearophile <bearophileHUGS lycos.com> writes:
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
Apr 13 2011
parent spir <denis.spir gmail.com> writes:
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
Apr 14 2011