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

Chris Eidhof chris at eidhof.nl
Wed Dec 9 16:11:36 CST 2015


Exactly! Just like multiple-if-let is the same as flatMap on optionals, this is a better syntax for flatMap on arrays. 

To make it more clear that it’s a nested loop, we could also consider:

for x in xs, for y in ys {
}

But I’m not sure if it actually is clearer. (You could totally still interpret this as a zip, rather than a flatMap).

Chris



> On 09 Dec 2015, at 16:51, Maxwell Swadling <maxs at apple.com> wrote:
> 
> 
>> On 9 Dec 2015, at 1:44 PM, Douglas Gregor via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>>> 
>>> On Dec 9, 2015, at 1:43 PM, Brent Royal-Gordon <brent at architechies.com <mailto: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/31b4dcaf/attachment.html>


More information about the swift-evolution mailing list