Search code examples
juliaarray-view

Creating views of user types in julia


The new julia 0.5 has improved support for views of arrays. Is it possible to use this functionality to allow views of custom types? E.g. so I could

immutable test
    a::Vector{Int}
    b::Vector{Int}
end

then define a getviewfunction that would e.g. give me a view of test like test(view(a,1:3), view(b,1:3) when passed 1:3 as the argument? (Just doing this creates a new test object where a and b are copies of the subarrays, which is not what I want). Thanks!


Solution

  • The key is that if you want your type to hold either Array or SubArray, you need to make it parametric. Otherwise it will be converted (copied) on construction of the new object.

    julia> immutable MyType{T}
               a::T
               b::T
           end
    
    julia> Base.view(mt::MyType, args...) = MyType(view(mt.a, args...), view(mt.b, args...))
    
    julia> mt = MyType(rand(5),rand(5))
    MyType{Array{Float64,1}}([0.791258,0.605581,0.126802,0.559727,0.156383],[0.773287,0.223521,0.926932,0.0301801,0.68872])
    
    julia> view(mt, 2:3)
    MyType{SubArray{Float64,1,Array{Float64,1},Tuple{UnitRange{Int64}},true}}([0.605581,0.126802],[0.223521,0.926932])