Julia made the choice to use a 1-based indexing scheme with a two-side including interval specification. This makes the transition from MATLAB to Julia easier. For some algorithms and for porting code from other languages, e.g. Python, it may make sense to on-demand switch to a 0-based indexing scheme with an end-excluding interval specification. This package provides this functionality in a hassle-free and explicit way using a macro. Renowned computer scientist Edsger W. Dijkstra wrote a short article arguing for this indexing scheme (see here and for more information about the topic here), that's where the package name comes from.
The module only exposes the macro @dsindex
. It can be used on an environment
or single expression and always works with the local variables:
using DijkstraIndexing
A = range(0, 3);
@dsindex b = A[0];
@assert b == 0
# Use it on sections of code and with arbitrary nested or slice expressions.
B = range(1, 2);
@dsindex begin
c = A[B[0+1]-1];
d = B[1:end];
end
@assert c == 1
@assert d == 2:2
# ND-Arrays.
C = zeros((3, 3))
@dsindex e = C[0, 0];
@assert e == 0
Slicing expressions are end-excluding.
Steps != 1 are supported. end
refers to the position after the last array
element, making the notation concise. That means, that A[end]
will throw an
exception and the last sequence element is accessed with A[end-1]
(this is
consistent with, e.g., Python access for A[-1]).
For the pull request, see here. If you can create your own objects and use them in your own library, this may be the best solution. If you receive objects to work with from another library, however, and do not want to wrap them or have to pass objects to a library that doesn't support general iterators (yet), problems may arise.
Since the macro is executed at compile time to rewrite the code, there's no runtime overhead.
This code is based on a gist by Pablo Winant.