Type instability in list comprehensions

mwallerb
Wed, 31 Jul 2024 12:31:06 +0000
General Usage

Consider the following code:

julia> x = [1, 2];
julia> y = Float64[];
julia> [xi * yi for xi in x for yi in y]
Any[]

julia> f(x, y) = [xi * yi for xi in x for yi in y]; f(x, y)
Float64[]

so the whole thing is type-unstable. Even more surprisingly, pasting the arguments into the comprehension resolves it:

julia> [xi * yi for xi in [1,2] for yi in Float64[]]
Float64[]

One way to resolve this is to use map together with product:

julia> vec(map(((xi,yi),) -> xi*yi, Iterators.product(x, y)))
Float64[]

which is clunky and annoying. This, to me, seems to be a straight-forward julia bug, which caused all sorts of nasty surprises to me. Why does julia behave that way?

Edited to add: note that all of these example are type-stable if y is non-empty:

julia> y = [3.0];
julia> [xi * yi for xi in x for yi in y]
4-element Vector{Float64}:
  3.0
  6.0

47 posts - 12 participants