[swift-dev] C-style For Loops

Dave Abrahams dabrahams at apple.com
Fri Feb 19 20:52:06 CST 2016


Sorry to have left this so long; I'm just catching up.

on Sat Dec 19 2015, Brent Royal-Gordon <brent-AT-architechies.com> wrote:

>> I personally liked the original free-function syntax—"stride(from:
> -50, to: 50, by: 9)".  When we got protocol extensions, we decided
> we'd prefer methods everywhere except in a few special cases, and this
> clearly falls outside those criteria.
>
> I don't know about that—in `stride(from: -50, to: 50, by: 9)`, I don't
> see any particular reason to privilege the `from` over the `to`. 

Me neither!  I'm just saying, the criteria we used to decide which
things could remain non-methods would not have allowed us to keep stride
this way.  We would need to have agreement on some principle that would
allow this form.

> I mean, I suppose `from` always starts the seqeunce whereas `to`
> doesn't always appear in it, but they still feel like peers which
> equally define the operation as a whole. 

Yes, but consider a.appendingContentsOf(b) or (sorry for bringing this
up) x.union(y).  I, at least, don't think those should be free functions.

I think the reason stride feels different is that it's weird for a
method on a scalar value to produce something with higher
dimensionality.

> This has definitely always bothered me about Swift 2.
>
> Incidentally, I just thought of another issue with using negative
> values with normal intervals to walk backwards: What does
> `(10..<20).by(-2)` mean? A naive implementation would probably give
> you this:
>
> 	[20, 18, 16, 14, 12, 10]
>
> It *should* mean this, which would not be useful terribly often:
>
> 	[18, 16, 14, 12, 10]

Great point, to say nothing of (10..<19).by(-2)! (does it start at 18 or 19)?

I think it *should* mean something useful... but I don't know why
you think one is more useful than the other.

Certainly, (10..<19).by(2).reversed() is unambiguous.  I think it would
have a nice symmetry if you could say that:

    r.by(-x).reversed() == r.by(x)
    r.by(x).reversed() == r.by(-x)

Would those be useful semantics in your eyes?

> Meanwhile, you really want to be able to get this, but the types and
> operators for an open-start interval don't currently exist:
>
> 	[20, 18, 16, 14, 12]

I don't understand why “you really want to be able to get this” from (10..<20).by(-2).

Wouldn't (12...20).by(-2) be a reasonable way to get there?

> I wonder if intervals might need another look, and maybe a redesign to
> make them more general.

-- 
-Dave


More information about the swift-dev mailing list