繁体   English   中英

Julia:类型稳定性使用 base.ntuples function

[英]Julia: type stability using the base.ntuples function

我最近开始使用 Julia,目前在打字的某些方面苦苦挣扎。 I am trying to define a type TensorTrain ( https://www.researchgate.net/profile/Ivan_Oseledets2/publication/220412263_Tensor-Train_Decomposition/links/5bbfb5c5299bf1004c5a56e3/Tensor-Train-Decomposition.pdf ), but I cannot get one of the methods我定义为稳定:

abstract type AbstractTensorTrain <: Any end

struct TensorTrain{T<:AbstractFloat} <: AbstractTensorTrain
    cores::Vector{Array{T,3}}
end

Base.size(t::TensorTrain, d::Int) = size(t.cores[d],2)
Base.size(t::TensorTrain) = ntuple(d->size(t,d),length(t.cores))

但是,如果我运行:

@code_warntype TensorTrain([rand(2,3,4)]);

我得到:

Variables
  #self#::Core.Compiler.Const(size, false)
  t::TensorTrain{Float64}
  #19::var"#19#20"{TensorTrain{Float64}}
  d::Int64

Body::Tuple{Vararg{Int64,N} where N}
1 ─ %1 = Base.getproperty(t, :cores)::Array{Array{Float64,3},1}
│        (d = Main.length(%1))
│   %3 = Main.:(var"#19#20")::Core.Compiler.Const(var"#19#20", false)
│   %4 = Core.typeof(t)::Core.Compiler.Const(TensorTrain{Float64}, false)
│   %5 = Core.apply_type(%3, %4)::Core.Compiler.Const(var"#19#20"{TensorTrain{Float64}}, false)
│        (#19 = %new(%5, t))
│   %7 = #19::var"#19#20"{TensorTrain{Float64}}
│   %8 = Main.ntuple(%7, d)::Tuple{Vararg{Int64,N} where N}
└──      return %8

为什么是这样?

因为d = length(t.cores)仅在运行时才知道,所以ntuple无法静态推断N参数。 有一种方法采用Val ,这在其他情况下对类型稳定性很有用,但在这里它不会改变任何东西—— d仍然是动态的。

不过,您可以将cores NTupleStaticVector (它们实际上是相同的东西),那么这将起作用。 但在深入研究类型级编程之前,请检查它是否真的有影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM