JuliaArrays / StaticArrays.jl

Statically sized arrays for Julia
Other
772 stars 150 forks source link

Summing two `FieldVectors` produces an `SArray` #729

Closed kmsquire closed 4 years ago

kmsquire commented 4 years ago

Example:

julia> struct Point3D <: StaticArrays.FieldVector{3, Float64}
           x::Float64
           y::Float64
           z::Float64
       end

julia> a = Point3D(rand(3)); b = Point3D(rand(3)); a+b
3-element StaticArrays.SArray{Tuple{3},Float64,1,3} with indices SOneTo(3):
 0.31581254718043894
 0.7451396786025122
 0.4810013436998537

Obviously, it's not hard to change it back into a Point3D.

I'm wondering if it's reasonable and feasible for this to be automatic?

For example, is it as simple as defining + for FieldVector`s? Are there good reasons not to do this?

(Presumably this definition would propagate to sum, mean, etc.)

c42f commented 4 years ago

For your type, you can do this by defining the trait:

StaticArrays.similar_type(::Type{Point3D}, ::Type{Float64}, ::Size{(3,)}) = Point3D

This may be possible to fix in general, but the dispatch is tricky to get right. I think it's just about possible though, let me give it a try.

c42f commented 4 years ago

That is, I think we can "do the right thing" for user defined but non-parametric FieldArrays. For the parametric case I don't think there's any way for us to do this.

PR is up: #731