[swift-evolution] C-style For Loops
Roland King
rols at rols.org
Sat Dec 5 05:28:34 CST 2015
> On 5 Dec 2015, at 18:27, Tyler Cloutier <cloutiertyler at aol.com> wrote:
>
> Hmm, yeah, that is definitely a good point. It can be easy enough to throw a continue into a while loop an completely skip the increment step. Of course you could add syntax to a while loop to allow for block/loop scoping of variables and then it might be tempting to add some finally logic to ensure that the incrementing is never skipped. Which, then what you have is a C style for loop with unfamiliar/unprecedented syntax, which would be silly.
Yes - I’m still thinking it through. while() is really a special case of the c-style for, just without the initializer and the pre-test increment (which I don’t like calling increment because it’s far more useful than that). The fact it calls the increment code every time before the test, with the notable exception of the first time, makes for a powerful sequence of test-do-increment-test-do-increment-test .. which while() alone doesn’t quite replicate. A continue in a for loop doesn’t translate well into a while() at all, obviously you can do it with nested ifs and other means but I think the power of the sequence for() gives you along with continue and break lets you write simple, understandable loop code.
So I’m not convinced by the argument that where you see a for() you can write a while() with a bit of code shuffling, for() is more powerful than while(), while() is the special case.
So that moves on to for .. in. That looks persuasively like a syntax which you can always change a C-style for into. And of course you can, you can make a generic generator which takes a few closures and does exactly what the c-style for does if you want. It’s easy however to just think in terms of things which have natural generators, 1..<n, an array of things, and when you use those with for .. in you get a very understandable line of code
for var element in myArray {}
is very clear because Array has a natural generator. Under the hood this is of course sugar for a c-style for loop where the initialisation and increment are predefined.
In other non-natural-generator cases, turning things into generators in order to use them with for .. in makes the code harder to read and understand. I brought up iterating floats, some of Matthijs’ examples from a couple of mails ago really would look a bit nasty shoehorned into an iterator paradigm so for .. in could un-shoehorn them again and turn them into the original for test-do-modify-test-do-modify-test he started with.
I’ve now had my 2c twice - I will be quiet.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151205/52a625de/attachment-0001.html>
More information about the swift-evolution
mailing list