Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 211
2Cubed Avatar asked Aug 15 '16 00:08

2Cubed


1 Answers

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)]
like image 156
Tasos Papastylianou Avatar answered Nov 02 '22 19:11

Tasos Papastylianou