56 points · by DaNmarner · 8y ago · 29 comments
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.
Given that this is basic Swift, the complaint makes no sense:
let a = Array(1..<5, 3..<5, where: { n, _ in n % 2 == 0 })
{ ($0, $1) }
// [(2,3),(2,4),(2,5) ...
let a = Array(1..<5, 3..<5) { ($0, $1) }
// [(1,3),(1,4),(1,5),(2,3),(2,4) ...What we have here is an array constructor, which takes one or more ranges as its arguments. The named `where:` argument provides the filter closure and the final argument is the map, using standard trailing closure syntax.
In fact, other than the missing implementation of the constructor, this would be perfectly legal Swift code today.
I'm not sure what's there to be confused about. `x..<y` describes an open range (including x, excluding y). `{x, y in ... }` is normal Swift closure syntax, where `x` and `y` are the arguments; you can also use positional arguments as in `{ ($0, $1) }` instead.
If the final argument of a function is a closure, it can be (as in Ruby) be written after the closing parenthesis of the function call.
The proposed Swift solution just looks like Perl level line noise. The only good thing about it is the processing being done in a block at the end.
⇒ 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.Neither is an improvement over the other. Sometimes it's more important to have the results up front fast, sometimes generating them on demand is better.
This.
> Nothing except local variable names (and nested macro capture names) is hygienic in macro_rules in fact.
It's a thing that's being fixed in the new macro systems, yeah.