Setting up a struct to act as a scalar in arithmetical expressions is easy. For example:
mutable struct D <: Number; v; end
Base.promote_rule(::Type{D}, ::Type{T}) where T = T
Base.convert(::Type{T}, d::D) where T <: Number = T(d.v)
d = D(3.5)
d + 4.7 # Gives 8.2 as expected
However, when I try to use a struct like a vector I cannot get it to work. For example I tried:
mutable struct F <: Number; v; end
Base.promote_rule(::Type{F}, ::Type{T}) where T = T
Base.convert(::Type{T}, f::F) where T <: Number = T.(f.v)
Base.convert(::Type{Vector{T}}, f::F) where T <: Number = T.(f.v)
f = F([3.5, 3.4])
f + [1.1, 2.2] # This gives an error
And the last line gives the error:
ERROR: LoadError: MethodError: no method matching +(::F, ::Vector{Float64})
For element-wise addition, use broadcasting with dot syntax: scalar .+ array
The function `+` exists, but no method is defined for this combination of argument types.
Closest candidates are:
+(::Any, ::Any, ::Any, ::Any...)
@ Base operators.jl:596
+(::Array, ::Array...)
@ Base arraymath.jl:12
+(::Number, ::LinearAlgebra.UniformScaling)
@ LinearAlgebra ~/.julia/juliaup/julia-1.11.2+0.aarch64.apple.darwin14/share/julia/stdlib/v1.11/LinearAlgebra/src/uniformscaling.jl:145
Note: Dot syntax does not work here and in any case I want to be able to use the standard notation (no dot needed to add vectors).
What is the best way to solve this?