Hey,
I cannot come up with a minimal example yet, but I encountered that my function return was type unstable because of such a construct:
function foo(x)
# some code
y = (1, 2) # first
y = [x[1] for i in x] # second
# more code
return g(y)
end
The first y
has a different type than the second y
. Deleting the first y
resulted in perfectly type-stable code, leaving it there, resulted in type-unstable code (at least @code_warntype
warned me).
So I was wondering why the first y
introduces difficulties since I didnβt use it actually and it has been there by mistake, but the function output is of course the same because the first y is never used.
I can come up with similar code, however it doesnβt fail completely with the output type, but the type of y
is a union.
julia> function f(x::AbstractArray{T, N}) where {T, N}
y = (1, 2)
y = [x[1] for i in x]
return y
end
f (generic function with 1 method)
julia> @code_warntype f([1,2,3])
Variables
#self#::Core.Const(f)
x::Vector{Int64}
#12::var"#12#13"{Vector{Int64}}
y::Union{Tuple{Int64, Int64}, Vector{Int64}}
Body::Vector{Int64}
1 β (y = Core.tuple(1, 2))
β %2 = Main.:(var"#12#13")::Core.Const(var"#12#13")
β %3 = Core.typeof(x)::Core.Const(Vector{Int64})
β %4 = Core.apply_type(%2, %3)::Core.Const(var"#12#13"{Vector{Int64}})
β (#12 = %new(%4, x))
β %6 = #12::var"#12#13"{Vector{Int64}}
β %7 = Base.Generator(%6, x)::Base.Generator{Vector{Int64}, var"#12#13"{Vector{Int64}}}
β (y = Base.collect(%7))
βββ return y::Vector{Int64}
julia> function f(x::AbstractArray{T, N}) where {T, N}
#y = (1, 2)
y = [x[1] for i in x]
return y
end
f (generic function with 1 method)
julia> @code_warntype f([1,2,3])
Variables
#self#::Core.Const(f)
x::Vector{Int64}
#14::var"#14#15"{Vector{Int64}}
y::Vector{Int64}
Body::Vector{Int64}
1 β %1 = Main.:(var"#14#15")::Core.Const(var"#14#15")
β %2 = Core.typeof(x)::Core.Const(Vector{Int64})
β %3 = Core.apply_type(%1, %2)::Core.Const(var"#14#15"{Vector{Int64}})
β (#14 = %new(%3, x))
β %5 = #14::var"#14#15"{Vector{Int64}}
β %6 = Base.Generator(%5, x)::Base.Generator{Vector{Int64}, var"#14#15"{Vector{Int64}}}
β (y = Base.collect(%6))
βββ return y
I would be very happy if someone could point me in the right direction why that is problematic.
Thanks,
Felix