Hello there, say I want to create a new type which is basically the same of Array{Float64, 1} except for the behaviour for one operator (for example +).
What I’m doing now is the following. First create a new mutable type MyVec
That feature does not exist in Julia itself. There are approaches that can ease the work.
import Base: length
import LinearAlgebra: dot
struct MyVec{T} <: AbstractVector{T}
vec::Vector{T}
end
# required by the AbstractArray interface
Base.size(x::MyVec) = size(x.vec)
Base.getindex(x::MyVec, i::Int) = getindex(x.vec, i)
Base.setindex!(x::MyVec, v, i::Int) = setindex!(x.vec, v, i)
# your customization of +
Base.:(+)(v::MyVec, u::MyVec) = ...
Base.:(+)(v::MyVec, u::Vector{Float64}) = v + MyVec(u)
Base.:(+)(v::Vector{Float64}, u::MyVec) = MyVec(v) + u
for F in (:length,) # add other appropriate unary functions
@eval begin
$F(v::MyVec,) = length(v.v)
end
end
for F in (:dot,) # add other appropriate binary functions
@eval begin
$F(v::MyVec, u::MyVec) = $F(v.v, u.v)
$F(v::MyVec, u::Vector{Float64}) = $F(v.v, u)
$F(v::Vector{Float64}, u::MyVec) = $F(v, u.v)
end
end
``
Creating a new type seems a way to keep the code cleaner (I also don’t want to change show behaviour for Array) but I’ll probably stick to Array and create only the new functions
julia> struct MyVec <: AbstractVector{Float64}
v::Vector{Float64}
end
julia> MyVec([0.0, 0.0, 0.0])
Error showing value of type MyVec:
ERROR: MethodError: no method matching size(::MyVec)
Closest candidates are:
size(::AbstractArray{T,N}, ::Any) where {T, N} at abstractarray.jl:38
size(::Base.AsyncGenerator) at asyncmap.jl:409
size(::Core.Compiler.StmtRange) at show.jl:1874
...
That happens on showing the structure, add ; at the end of the line to not show it. To fully implement the iteration interface see Interfaces · The Julia Language