Unclear documentation of `collect`? (similarity and difference with brackets)


I just came across the docstring of collect (Collections and Data Structures · The Julia Language) and I’ve got the feeling that the second usage example would need some more explanation, or is it just me?

julia> [x^2 for x in 1:8 if isodd(x)]
4-element Vector{Int64}:

(the first example is more simply collect(1:2:13))

The way I understand this example is that “if you put a Generator inside brackets, you get the same result as collect(…)'ing that generator”. Is my interpretation correct?

Also, if my interpreation is correct, I believe that mentioning the [...] notation/operator would require an additional warning, because the similarity is partial:

  • indeed [i for i in 1:3] and collect(i for i in 1:3) both returns the same 3-element Vector{Int64}
  • however, [1:3] returns a 1-element Vector{UnitRange{Int64}}, while collect(1:3) returns the same 3-element Vector{Int64} as before
1 Like

The bracket generator syntax in your example more or less ends up lowering to this:

f(x) = x^2
itr = 1:8
filterfunc(x) = isodd(x)
gen = Base.Generator(f, Base.Filter(filterfunc, itr))

You can take a look at the exact lowered code with Meta.@lower.

So yes, it is exactly the same as calling collect on a Base.Generator.

Only bracket expressions with a for in them are generator expressions - without them, they are just syntax for array literals.

Thanks for the explanation, but my question was more about the clarity of the documentation (I’ve updated the topic title to emphasize this).

I’ve now created the Pull request #50619 with a proposition to expand the docstring of collect.