[swift-evolution] Extending the for loop to have multiple clauses

Wed Dec 9 15:51:40 CST 2015

```> On 9 Dec 2015, at 1:44 PM, Douglas Gregor via swift-evolution <swift-evolution at swift.org> wrote:
>
>>
>> On Dec 9, 2015, at 1:43 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
>>
>>>> I think it could be really nice to extend the for-loop so that it can have multiple clauses. Much like in the if-let with multiple clauses, I could imagine a for-loop with multiple clauses:
>>>>
>>>> var cards: [(Suit,Rank)] = []
>>>> for x in suits, y in ranks {
>>>> cards.append((x,y))
>>>> }
>>>
>>>
>>> Isn’t this just
>>>
>>> 	for (x, y) in zip2(suits, ranks) {
>>> 	}
>>>
>>> ?
>>
>> No, apparently it’s supposed to be all permutations of both types. But I too read it as syntactic sugar for a zip, which I think is a great reason not to add this syntax.
>
>
> Ah. In that case, I’d much rather have a library function that indicates that we’re getting all permutations. This doesn’t feel like it belongs in the language at all, but in the library.
>
> 	- Doug
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>

We do have this library function, it is flatMap.

The desired feature here seems to be desugaring for loops

for x in xs, y in ys, z in zs {
...
}

into:

xs.flatMap { x in ys.flatMap { y in zs.map { z in ... } } }

So as above you would get:

suits.flatMap { x in ranks.map { y in cards.append((x,y)) } }

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151209/40f6ee49/attachment.html>
```