[swift-evolution] Proposal: for loops with return values

Craig Cruden ccruden at novafore.com
Thu Jan 14 15:10:36 CST 2016


I believe this is the same as Scala’s for-comprehension….. and Scala’s for-comprehension is actually just syntactic sugar for a combination of flatMap, map and withFilter.

Although harder to read for many… it likely could be written similarly in Swift.  

i.e. 

>> for row in 0..<m { for col in 0..<n where row+col < 5 { yield (row,col) } }

in Scala is

for {
   row <- 0 to m 
   col <- 0 to n
   if row+col < 5
} yield (row, col)

which is actually (after the compiler is done with it):

(0 to m).flatMap(x => (0 to n).withFilter(y => x + y < 5).map(y => (x, y)))

I have not tried to do it in the playground but I would expect since I believe all the functions are available in Swift.

Note: 0 to m // is a range in Scala
	withFilter is a filter which does not copy the contents of what it is filtering…. it is just applying the filter as needed when mapping.






> On 2016-01-15, at 3:35:23, Félix Cloutier via swift-evolution <swift-evolution at swift.org> wrote:
> 
> This has been proposed before and Chris said that it would be out of scope for Swift 3. There is definitely interest in this area though.
> 
> Félix
> 
>> Le 14 janv. 2016 à 15:30:07, Amir Michail via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> a écrit :
>> 
>> These would be like the unrolled versions of Python’s generator expressions.
>> 
>> Examples:
>> 
>> let a:[Int] = for x in l { yield x*2 }
>> 
>> let b:[(Int,Int)] = for row in 0..<m { for col in 0..<n { yield (row,col) } }
>> 
>> let c:[(Int,Int)] = for row in 0..<m { for col in 0..<n where row+col < 5 { yield (row,col) } }
>> 
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> 
> _______________________________________________
> 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/20160115/5eb8dfd5/attachment.html>


More information about the swift-evolution mailing list