List Comprehension in Swift

  • I really dislike the proposed way to do this. If this is "Swifty", give me something else.

    The Haskell list comprehension made sense to me the first time I saw it, but there is no way I'd know what the mess in the article was doing until someone explained to me.

    Design has to come first. You can't just go with what's "Swifty" if that doesn't convey what's happening in a reasonable fashion.

  • List comprehension is a bad idea, IMO. They were an improvement over not having anything like it, but python has improved over it (https://wiki.python.org/moin/Generators)

    ⇒ Generator expressions are the way to go. They would give you the sequence of elements without generating the (potentially enormous) data structure.

    From there, methods to reify the items in a sequence would give you your list, array, or dictionary, where needed.

    So, for Swift, I wouldn’t use

        Array(1..<5, 3..<5) { ($0, $1) }
    
    but the slightly longer

        Array(for i in 1..<5, j in 3..<5 yield (i,j))
    
    I’m not sure that is easy to fit in the existing parser, though. If it can be fit in, I would allow that code in ‘normal’ nested for loops, too.

  • > (Can’t wait until we can have variadic generic parameters!)

    This.

  • Can someone explain the n modulo operation to me?

  • > List comprehension should be no stranger to a Python or (and?) Haskell user. It’s a really compact syntax that deals with Cartesian product [emphasis mine] of lists.

    Ugh, no. I fail to see where the Cartesian product is in::

        [(x,y,z) | x <- [1..5], y <- [x..10], z <- [x..y]]
    
    ---

    @dennisvennink

    What you feel doesn't matter. It's not a zip.

  • undefined