What if the `if` filter from generator statements worked in for loops too?

Julia lets you append if to a list comprehension to filter it inline:

julia> [j for j in rand(1:100, 20) if iseven(j)]
7-element Vector{Int64}:
 12
 82
 64
 58
 84
 76
 32

Sometimes you want to do something similar in a for loop. Here is one way:

julia> for j in rand(1:100, 20)
           if iseven(j)
               println(j)
           end
       end
42
38
50
82
76
22
18
60
86
48

Here is another:

julia> for j in (j for j in rand(1:100, 20) if iseven(j))
           println(j)
       end
66
24
88
68
94
28
90
40
20
28

Would there be any issues with implementing the following syntax for the same?

julia> for j in rand(1:100, 20) if iseven(j)
           println(j)
       end


ERROR: syntax: incomplete: "for" at REPL[24]:1 requires end
Stacktrace:
 [1] top-level scope
   @ none:1

(The purpose of my question is less of a feature request and more to gain understanding of how Julia parses these kinds of if/end blocks.)

Might be useful for reference:
https://docs.julialang.org/en/v1/manual/arrays/#Generator-Expressions

This is simply equivalent to

for j in rand(1:100, 20)
    if iseven(j)
        println(j)
    end

so it complains about the missing end for the for-loop. So the syntax does already work, you just need an extra end. There’s no real way around this either since otherwise it would be ambiguous where which block ends.

2 Likes

So why isn’t end required in the generator expression [j for j in 1:100 if iseven(j) end]?

I mean, I know that the answer is “because it’s a generator expression and not an if block”, but if Julia can figure out that this is a generator expression and not an if block, then would it be dangerous to have a syntactical rule that says “if if appears on the same line as a for loop declaration, treat it like you would in a generator expression”?

(Again, I’m not trying to be snarky here, just trying to improve my understanding by getting a sense for what is or isn’t possible and why.)

The difference is that the generator expression is unambiguously delimited by the ]. Yes, in theory we could make this dependent on whether there’s a newline or a space before the if, but I don’t think it’s worth the inconsistency compared to how blocks are nested everywhere else. Contrary to Python, we generally try to avoid syntactically significant whitespace.

5 Likes