2Cubed
2Cubed

Reputation: 3551

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]  # alternatively, map!(x -> x^2, l)
# [36, 49, 64, 81]

Is this possible in Julia?

Upvotes: 16

Views: 7372

Answers (1)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22255

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)]

Upvotes: 31

Related Questions