Example 1 – the OffsetArrays.jl package

The OffsetArrays.jl package allows us to define arrays with arbitrary indices rather than the standard linear or cartesian style indices. A fun example is to use a zero-based array, just like the ones you may find in other programming languages:

To understand how this works, we need to dig into the source code. Let's keep things concise and review just a portion of the code:

struct OffsetArray{T,N,AA<:AbstractArray} <: AbstractArray{T,N}
parent::AA
offsets::NTuple{N,Int}
end

Base.parent(A::OffsetArray) = A.parent

Base.size(A::OffsetArray) = size(parent(A))
Base.size(A::OffsetArray, d) = size(parent(A), d)

Base.eachindex(::IndexCartesian, A::OffsetArray) = CartesianIndices(axes(A))
Base.eachindex(::IndexLinear, A::OffsetVector) = axes(A, 1)

The OffsetArray data type is composed of the parent and offsets fields. In order to satisfy the AbstractArray interface, it implements some of the basic functions, such as Base.sizeBase.eachindex, and so on. Since these functions are simple enough, the code just forwards the call to the parent object manually.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.68.14