这是一个简化的例子:
odot(A::Matrix, B::Matrix) = A * B
# using unicode alias ⊙
odot(A::Matrix, B::Vector) = reshape(A ⊙ reshape(B,size(A)), length(B))
⊙ = odot
julia> @code_warntype rand(3,3) ⊙ rand(9)
Variables:
#self#::#odot
A::Array{Float64,2}
B::Array{Float64,1}
Body:
begin
return (Main.reshape)((A::Array{Float64,2} ⊙ $(Expr(:invoke, LambdaInfo for reshape(::Array{Float64,1}, ::Tuple{Int64,Int64}), :(Main.reshape), :(B), :((Core.tuple)((Base.arraysize)(A,1)::Int64,(Base.arraysize)(A,2)::Int64)::Tuple{Int64,Int64}))))::Any,(Base.arraylen)(B::Array{Float64,1})::Int64)::Any
end::Any
# using odot
odot(A::Matrix, B::Vector) = reshape(odot(A,reshape(B,size(A))), length(B))
julia> @code_warntype rand(3,3) ⊙ rand(9)
Variables:
#self#::#odot
A::Array{Float64,2}
B::Array{Float64,1}
TS::Type{Float64}
Body:
begin
SSAValue(0) = $(Expr(:invoke, LambdaInfo for reshape(::Array{Float64,1}, ::Tuple{Int64,Int64}), :(Main.reshape), :(B), :((Core.tuple)((Base.arraysize)(A,1)::Int64,(Base.arraysize)(A,2)::Int64)::Tuple{Int64,Int64})))
# meta: location REPL[1] odot 1
# meta: location linalg/matmul.jl * 128
TS::Type{Float64} = $(QuoteNode(Float64)) # line 129:
SSAValue(1) = (Core.tuple)((Base.arraysize)(A::Array{Float64,2},1)::Int64,(Base.arraysize)(SSAValue(0),2)::Int64)::Tuple{Int64,Int64}
SSAValue(2) = (Core.ccall)(:jl_new_array,(Core.apply_type)(Core.Array,Float64,2)::Type{Array{Float64,2}},(Core.svec)(Core.Any,Core.Any)::SimpleVector,Array{Float64,2},0,SSAValue(1),0)::Array{Float64,2}
# meta: pop location
# meta: pop location
SSAValue(4) = $(Expr(:invoke, LambdaInfo for gemm_wrapper!(::Array{Float64,2}, ::Char, ::Char, ::Array{Float64,2}, ::Array{Float64,2}), :(Base.LinAlg.gemm_wrapper!), SSAValue(2), 'N', 'N', :(A), SSAValue(0)))
SSAValue(3) = (Core.tuple)((Base.arraylen)(B::Array{Float64,1})::Int64)::Tuple{Int64}
return $(Expr(:invoke, LambdaInfo for reshape(::Array{Float64,2}, ::Tuple{Int64}), :(Base.reshape), SSAValue(4), SSAValue(3)))
end::Array{Float64,1}
我想知道为什么在第一种情况下为什么类型推断在unicode上失败。
答案 0 :(得分:5)
在变量形式中定义函数时,需要确保将其声明为常量,以使其具有正确的类型信息作为全局。
const ⊙ = odot