Swapping components of structure "nominally"

I defined the following struture

struct AB{T}
A::T
B::T
end

with two components of the same numerical type. Sometimes I need to swap the two such that A=-B and B=A. Is there a way to avoid actual swapping the value and just “mark” the swapping such that subsequent computations will treat A as B and -B as A? I’m interested in storing an array of AB type as a StructArray{AB}, which makes sense to not actually swap the arrays.

How can this be done? I’m looking for something like the adjoint(::Matrix...) markup of numerical arrays. Thank you for any suggestions.

You can make a specialized wrapper type like:

julia> struct AB{T}
           A::T
           B::T
       end

julia> struct ABWrapper{T}
           ab::AB{T}
       end

julia> function Base.getproperty(obj :: ABWrapper{T}, field :: Symbol) where {T}
           if field === :A
               obj.ab.B
           elseif field === :B
               -obj.ab.A
           else
               getfield(obj, field)
           end
       end

julia> ab = AB(10, 20)
AB{Int64}(10, 20)

julia> abw = ABWrapper(ab)
ABWrapper{Int64}(AB{Int64}(10, 20))

julia> ab.A
10

julia> abw.A
20

julia> abw.B
-10

But I would sincerely just replace the object by one with the fields switched.

2 Likes