using Test
struct MyMatrix{MT<:AbstractMatrix}
M::MT
end
Base.:(*)(A::MyMatrix, x::Number) = MyMatrix(A.M * x)
function f(x)
# return [y / 10 for y in x]
return x * 10
end
# states = [rand_dm(10) for _ in 1:10]
states = [MyMatrix(rand(10, 10)) for _ in 1:10]
f(states)
@inferred f(states)
It detects type instability, since it is using broadcasting. But as soon as I use the comprehension, then everything works. Why?
Notice that the operation * itself is type-stable.
Notice also that the matrix can be any AbstractMatrix sparse, GPU, etc.
I cannot see that using a global const or a local scope makes any difference, neither on 1.10 nor on nightly. It also doesn’t make much sense that it would; the inference is made for the type present when the call is done. It’s something completely different to refer to a non-const global from inside a function, rather than a function argument, which is a common cause of type instability.
Thanks for correcting.
It seems the issue goes away by doing some things, which I wrongly attributed to the introduction of the local scope.
E.g. re-executing the struct definition makes this issue vanish.
julia> @inferred f(states);
ERROR: return type Vector{MyMatrix{Matrix{Float64}}} does not match inferred return type Any
Stacktrace:
[1] error(s::String)
@ Base ./error.jl:35
[2] top-level scope
@ REPL[7]:1
julia> struct MyMatrix{MT<:AbstractMatrix}
M::MT
end
julia> @inferred f(states);