Sum or fold over fields in a struct

Not sure which RGB type we are talking about (it doesn’t seem to be the one from Colors.jl) but you could try something like:

foldl(+, arr; init=RGB{Float64}(0.0,0.0,0.0))

That is fold/reduce the array via addition with a RGB{Float64} initial value.

Example with a simple fake RGB type:

julia> struct RGB{T}
           r::T
           g::T
           b::T
       end

julia> Base.:+(x::RGB, y::RGB) = RGB(x.r + y.r, x.g + y.g, x.b + y.b)

julia> arr = RGB{UInt8}.(rand(UInt8,10), rand(UInt8,10), rand(UInt8,10));

julia> typeof(arr)
Array{RGB{UInt8},1}

julia> foldl(+, arr; init=RGB{Float64}(0,0,0))
RGB{Float64}(894.0, 1321.0, 1086.0)
2 Likes