The question is related to the general topic of mutating immutables.
StaticArrays comes with a helpful convenience function setindex
, which allows modifying an array element at a given position and returning a new StaticArray, as far as I understand, presumably this is achieved without an additional memory allocation step.
I wonder if there something equivalent for CartesianIndex? It is a fairly common task (at least within my realm) to try and access nearest-neighbor indices.
I ended up writing the following function, which returns a CartesianIndex associated with a nearest-neighbor index, using Base.Cartesian macro.
@generated function hop(index::CartesianIndex{NDIMS},dir::Int64,lr::Int64) where {NDIMS}
quote
@ncall $NDIMS CartesianIndex d_t->
begin
if d_t==dir
if (lr==1)
index[d_t]+1
else
index[d_t]-1
end
else
index[d_t]
end
end
end
end
My question is whether there is a simpler “Julian” (whatever that means ) approach, possibly in the spirit of StaticArray’s setindex
in the context of CartesianIndex?
Snir