Julia 将许多标准方法扩展到新的自定义向量类型

Julia 将许多标准方法扩展到新的自定义向量类型,julia,Julia,我构建了一个新的向量类型: type MyType x::Vector{Float64} end 我想将许多标准方法(如加法、减法、元素比较法等)扩展到我的新类型。我是否需要为它们中的每一个定义一个方法定义,例如: +(a::MyType, b::MyType) = a.x + b.x -(a::MyType, b::MyType) = a.x - b.x .<(a::MyType, b::MyType) = a.x .< b.x +(a::MyType,b::MyTyp

我构建了一个新的向量类型:

type MyType
    x::Vector{Float64}
end
我想将许多标准方法(如加法、减法、元素比较法等)扩展到我的新类型。我是否需要为它们中的每一个定义一个方法定义,例如:

+(a::MyType, b::MyType) = a.x + b.x
-(a::MyType, b::MyType) = a.x - b.x
.<(a::MyType, b::MyType) = a.x .< b.x
+(a::MyType,b::MyType)=a.x+b.x
-(a::MyType,b::MyType)=a.x-b.x
.下面是一个使用以下内容的示例:


对于op in(+、:-、:.您可以继承自
AbstractArray
并定义一个非常小的接口,免费获取所有基本数组操作:

type MyType <: AbstractVector{Float64}
    x::Vector{Float64}
end
Base.linearindexing(::Type{MyType}) = Base.LinearFast()
Base.size(m::MyType) = size(m.x)
Base.getindex(m::MyType,i::Int) = m.x[i]
Base.setindex!(m::MyType,v::Float64,i::Int) = m.x[i] = v
Base.similar(m::MyType, dims::Tuple{Int}) = MyType(Vector{Float64}(dims[1]))

键入MyType可能是元编程之类的。@rickhg12hs我以前从未研究过元编程。我想是时候了……非常感谢。
type MyType <: AbstractVector{Float64}
    x::Vector{Float64}
end
Base.linearindexing(::Type{MyType}) = Base.LinearFast()
Base.size(m::MyType) = size(m.x)
Base.getindex(m::MyType,i::Int) = m.x[i]
Base.setindex!(m::MyType,v::Float64,i::Int) = m.x[i] = v
Base.similar(m::MyType, dims::Tuple{Int}) = MyType(Vector{Float64}(dims[1]))
julia> MyType([1,2,3]) + MyType([3,2,1])
3-element Array{Float64,1}:
 4.0
 4.0
 4.0

julia> MyType([1,2,3]) - MyType([3,2,1])
3-element Array{Float64,1}:
 -2.0
  0.0
  2.0

julia> MyType([1,2,3]) .< MyType([3,2,1])
3-element BitArray{1}:
  true
 false
 false