For .... if ... syntax?

I was just wondering what thoughts people have on the following syntax

for iter if cond
    #stuff here
end

which would basically be short for

for iter
    if cond
        #stuff here
    end
end

Obviously this isn’t necessary, but I don’t think it would hurt and it should be intuitive and “julian” since we already have this sort of thing for comprehensions, where something like [i for i = 1:10 if i%2 == 0] will return [2,4,6,8,10].

Any thoughts?

This would be a breaking change, since

for iter if cond
        # stuff
    end
end

is already valid syntax.

6 Likes

How about

for iter where cond
        # stuff
    end
end

?

where could be context-appropriate and is already a keyword.

Language design can of course be very subjective, but I think that adding basic syntax that is not necessary for a special case of something we already have is as anti-Julian as it gets.

We have perfectly fine, composable control flow building blocks for this purpose already. Alternatives include

for i in itr
    ...
    cond || continue
    ...
end

depending on what each ... does.

7 Likes

Personally, I think making for loops mirror comprehensions is pretty Julian. If we follow your logic, we should get rid of the conditional in the comprehension syntax.

[f(i) for iter if cond(i)]

doesn’t do anything that we can’t achieve with using filter or boolean indexing.

Aren’t comprehensions just shortcuts for writing a loop anyway? Maybe cut them out all together.

1 Like

Neither is not a good comparison. Using the [... for ... in ... if ...] syntax avoids creating temporaries for the unfiltered interim results, boolean indexing OTOH would require them. filter operates on existing iterators, the comprehension syntax creates iterators and collects them; a pretty common use case.

The point is not to avoid any kind of parallel solution — that neither desirable nor practical — but to have a small number of orthogonal building blocks that combine well. For this particular purpose, control flow already works very well.

On a somewhat related note, I admire how clean Julia is from a control flow perspective. Basic (non-coroutine) control flow has combounding (begin, ( ; )), two kinds of loops (for, while), branching and short-circuiting boolean ops, and the standard exception handling constructs. And that’s it! We can build the rest easily from these components. (Technically for is redundant once we have while, but it meshes so well with iteration that it is worth it).

2 Likes

This is starting to sound quite a lot like Ruby. I keep finding things like do A unless B if C hard to parse.

5 Likes