Extend many standard methods to a new custom vecto

2019-05-14 00:55发布

I build a new vector type:

type MyType
    x::Vector{Float64}
end

I want to extend lots of the standard methods, eg addition, subtraction, element-wise comparison, etc to my new type. Do I need to define a method definition for each of them, eg:

+(a::MyType, b::MyType) = a.x + b.x
-(a::MyType, b::MyType) = a.x - b.x
.<(a::MyType, b::MyType) = a.x .< b.x

or is there some syntactic short-cut I can use here?

标签: julia
2条回答
贼婆χ
2楼-- · 2019-05-14 01:09

Here's an example using Julia's Metaprogramming:

for op in (:+, :-, :.<)
    @eval ($op)(a::MyType, b::MyType) = ($op)(a.x, b.x)
end
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-05-14 01:20

You can inherit from AbstractArray and define a very small interface to get all the basic array operations for free:

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]))

Let's test this:

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
查看更多
登录 后发表回答