JuliaLang/julia

Add a "lazy" while guard to comprehension syntax

Open

#22,772 opened on Jul 12, 2017

View on GitHub
 (9 comments) (4 reactions) (0 assignees)Julia (5,773 forks)batch import
help wantedspeculative

Repository metrics

Stars
 (48,709 stars)
PR merge metrics
 (Avg merge 20d 6h) (157 merged PRs in 30d)

Description

I have found myself wanting to write something like:

X = [f(a) for a in iterator if cond1(a) while cond2(a)]

and have this return elements from the iterator until cond2(a) returns false. This would essentially be the same as:

X = []
for a in iterator
    !cond2(a) && break
    cond1(a) && push!(X, f(a))
end

Using while in this context looks and feels a lot like the functional takewhile function, uses an already existing keyword, and is to my eyes a lot less noisy than the explicit loop above.

There are a few StackOverflow questions that have asked for a similar functionality here https://stackoverflow.com/questions/44097910/killing-a-for-loop-in-julia-array-comprehension and here https://stackoverflow.com/questions/44101965/array-comprehension-with-a-random-output-in-julia/

Contributor guide