2Cubed 2Cubed - 3 months ago 21
Python Question

Conditional comprehension in Julia

In Python, there is the option to provide a condition for whether or not to include a specific item in a comprehension.

[x**2 for x in range(10) if x > 5]
# [36, 49, 64, 81]


It is possible to conditionally use function), but I have not yet found a way to entirely exclude values, other than
filter!
ing them outside of the comprehension.

l = collect(0:9)
filter!(x -> x > 5, l)
l = [x^2 for x in l] # alternately, map!(x -> x^2, l)
# [36, 49, 64, 81]


Is this possible in Julia?

Answer

It is possible in the latest Julia.

julia> [x^2 for x in 0:9 if x > 5]
4-element Array{Int64,1}:
 36
 49
 64
 81

Otherwise, yes, if you're using pre 0.5 you're stuck with:

[x^2 for x in filter((x) -> x > 5, 0:9)]