Julia - How to use Array comprehension with ternary operator to initialize a vector

Viewed 273

This is my desired behavior...

result = []
for element in iterable
    if(condition)
        push!(result, element)
    else 
        continue 
    end
end

But when using an array comprehension in Julia with a ternary operator, I'm not sure what the analogous "continue" would be aside from using nothing. Which results in undesired Vector{Union{Nothing, ...}}.

result = [(condition ? element : nothing) for element in iterable]

For example:

vec1 = []
for v in -1:1
    if(v==0)
        push!(vec1,v)   
    else 
        continue   
    end 
end 

returns

julia> vec1 
1-element Vector{Any}:
0

Meanwhile

vec2 = [(v==0 ? v : nothing) for v in -1:1]

returns

julia> vec2 = [(v==0 ? v : nothing) for v in -1:1]        
3-element Vector{Union{Nothing, Int64}}:
nothing
0
nothing

instead of just a normal Vector{Int64}

1 Answers

If you want to use an array comprehensions, you can use the if keyword:

julia> [x for x in -2:2 if iseven(x)]
3-element Vector{Int64}:
 -2
  0
  2

If you don't need to use an array comprehension, you can use filter:

julia> filter(iseven, -2:2)
3-element Vector{Int64}:
 -2
  0
  2

It is not possible to use a construct like: result = [(condition ? element : <SOMETHING>) for element in iterable] because this will always preserve the length of the input iterable. It is equivalent to a map, but it seems you really want a filter.

Related