For loop condition filter

Has anybody wanted something like this?

for x in 1:10 if x != 5
    println(x)
end

Here’s some less-than-ideal ways:

for x in (x for x in 1:10 if x != 5)
    println(x)
end
for x in 1:10
    x == 5 && continue
    println(x)
end
for x in filter(!=(5), 1:10)
    println(x)
end

Here is the ideal way:

for x in 1:10
    x != 5 && println(x)
end

You can write out an explicit if if you prefer.

Extra syntax to stuff this into the loop is probably unwarranted.

5 Likes
julia> println.(x for x in 1:10 if x != 5)

or for nicer REPL display

julia> println.(x for x in 1:10 if x != 5);
1 Like

And maybe a remark about the background:
In my view an iterator is an abstraction of a loop people might write. E.g. (x for x in 1:10 if x != 5) is the abstraction of writing a loop

for x in 1:10
    if x != 5
        ....
    end
end

but it does not make the vanilla loop obsolete or replace it.

3 Likes

Perhaps just personal preference, but I usually prefer to write this as

for x in 1:10
    x != 5 || continue
    ....
end

since it avoids an extra level of nesting.

4 Likes