Advice for structure


#1

Hi,

I am working with couples of vectors x,p where the size of x (resp. p) is fixed.
I thought about using

mutable struct Cp{T}
  x::Vector{T}
  p::Vector{T}
end

However, I would like to overload the operators so that if u = Cp(rand(3),rand(4)), I could do 3*u, v = copy(u) or compute u-2v for example.

Is there a good way for doing this?

Thank you for your help,

Best regards


#2

Yes (the short answer). In general, this is accomplished using type-directed dispatch with function signatures that use your type Cp{T}.

import Base: +, -, *

mutable struct Cp{T}
    x::Vector{T}
    y::Vector{T}
end

function (*)(a::Real, cp::Cp{T}) where {T}
     newx = a .* (cp.x)
     newy = a .* (cp.y)
     result = Cp{T}(newx, newy)
     return result
end

function (-)(a::M, b::M) where {T, M<:Cp{T}}
    @assert length(a.x) == length(b.x) == length(a.y) == length(b.y)
    newx = a.x .- b.x
    newy = a.y .- b.y
    result  = Cp{T}(newx, newy)
    return result
end


julia> a = Cp([1,2,3],[4,5,6])
Cp{Int64}([1, 2, 3], [4, 5, 6])

julia> b = 3a
Cp{Int64}([3, 6, 9], [12, 15, 18])

julia> 8a - 2b
Cp{Int64}([2, 4, 6], [8, 10, 12])


#3

Wow, you are fast.

Thank you for your help.