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

thorsten at portableinnovations.de thorsten at portableinnovations.de
Thu Dec 10 06:47:07 CST 2015


The advantage of not having to nest is that I can do all these nice monadic things with its. Just look at Scala's for-expression which does exactly that, mimicking Haskell's do-notation.
I would love support for that in Swift.

-Thorsten

> Am 09.12.2015 um 23:11 schrieb Chris Eidhof via swift-evolution <swift-evolution at swift.org>:
> 
> 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> 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
>>> 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)) } }
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151210/e1277fbb/attachment.html>


More information about the swift-evolution mailing list