[swift-evolution] Proposal: Python's list, generator, and dictionary comprehensions

T.J. Usiyan griotspeak at gmail.com
Thu Dec 17 19:11:45 CST 2015


Using a sequence meant to represent a [Cartesian Product](
https://github.com/griotspeak/CartesianProduct)

You can write this

        for (i, j) in (0...10) • (0...10) where i + j < 8 {

            print(i)

        }



I am not dead set on the • operator as cartesian product and only added it
back in to demonstrate that this can be  *this* pretty.


TJ

On Thu, Dec 17, 2015 at 7:41 PM, Al Skipp via swift-evolution <
swift-evolution at swift.org> wrote:

> On 17 Dec 2015, at 20:25, Liam Butler-Lawrence via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Comprehensions are great in Python. However, Swift can already do all of
> these things via for...in, map() and/or generate().
>
>
> Whether Comprehensions should be introduced to the language is worth
> consideration (Are they vital? Probably not). But I don’t find the Swift
> examples using ‘for' statements particularly compelling. The ‘for’
> statement needs to declare a mutable variable which is updated from within
> the loop. It works, but it’s not particularly elegant.
>
> var l2: [(Int, Int)] = []
> for x in 1...10 {
>   for y in 1...10 where (x + y) < 8 {
>     l2.append((x, y))
>   }
> }
>
> It could be achieved using an expression, but it’s pretty horrible too for
> several reasons:
>
> let l3 = (1...10).flatMap { x in
>   (1...10).map { y in (x,y) }
> }.filter { (x, y) in x + y < 8 }
>
> (Maybe there’s a more elegant solution?)
>
> If Swift had Comprehensions, they probably wouldn’t look exactly like the
> example below, but in my opinion it’s superior to the 2 code samples above.
>
> l2 = [(x,y) for x in range(10) for y in range(10) if x + y < 8]
>
> Al
>
> _______________________________________________
> 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/20151217/13694e5d/attachment.html>


More information about the swift-evolution mailing list