3 ms·
> I'm not even sure what the result of a looping expression should be >Break and return statements have no useful results The result of a looping expression c
by jpfed 12y ago
> I'm not even sure what the result of a looping expression should be
>Break and return statements have no useful results
The result of a looping expression could be specified by its break!
var myNeedle = foreach(var maybeNeedle in myHaystack) {
if (maybeNeedle.isTheNeedle()) break maybeNeedle;
}
if (myNeedle != null) print("I found " + myNeedle.toString());
- munificent 12y agoI like this idea. :)
- twic 12y agoI quite often find myself writing code like (in Java): Fruit edibleFruit = null; for (Fruit f: basket) { if (f instanceof Banana) { if (!f.isDiscoloured()) { edibleFruit = f; break; } } else { if (!f.isMouldy()) { edibleFruit = f; break; } } } And getting rid of the nasty assign/break pairs by extracting a method: Fruit edibleFruit = edible(basket); Fruit edible(Collection<Fruit>: basket) { for (Fruit f: basket) { if (f instanceof Banana) { if (!f.isDiscoloured()) return f; } else { if (!f.isMouldy()) return f; } } return null; } But your idea would let me clean up without having to extract a method (here, in a hypothetical Java-with-value-bearing-break): Fruit edibleFruit = for (Fruit f: basket) { if (f instanceof Banana) { if (!f.isDiscoloured()) break f; } else { if (!f.isMouldy()) break f; } } You need to have a story about what happens if there isn't a break - if the loop exits normally. You could implicitly return null, but that's a terrible idea. Better would be to require else clauses on value-returning loops (a bit like the else clauses that Python allows on try blocks): Fruit edibleFruit = for (Fruit f: basket) { if (f instanceof Banana) { if (!f.isDiscoloured()) break f; } else { if (!f.isMouldy()) break f; } } else null; Yes, i'm still returning null here, but at least i have to do it explicitly, which makes me feel bad about it and think about finding a better alternative!