Optionally strongly typed array indexes
bearophile via Digitalmars-d
digitalmars-d at puremagic.com
Wed Jun 4 02:43:15 PDT 2014
Mason McGill:
> There's definitely a tension between writing generic code
> (NumPy-style, operating on abstract dimensions) and safe code
> (operating on dimensions with semantics;
While you can shove lot of different kind of code inside the
matrix-based style of coding of APL, NumPy and so on, I find
there is also plenty of code that is more naturally expressed
with loops or with higher order functions as map/filter.
And sometimes in D you want to implement the array processing
functions (the ones of NumPy that are written in Fortran, C,
C++), using loops. The non-built-in data structures need to be
implemented in D, so strong typing for indexes helps you write
those routines more correctly.
> It seems to me that the users who may benefit most from this
> feature are likely to be using non-built-in data structures.
Strongly typed indexes are useful not just for handling 2D or 3D
matrices, but also when you need to use two or more 1D arrays, to
avoid confusing indexes of an array with the indexes of the
other. Such situations are common even in non numerical D code. I
write plenty of code like this.
> For example, you mention interpreting the first level of array
> nesting as rows and the second as columns, implying you are
> treating the nested arrays as a matrix
Right.
You can give strong typing to indexes of a matrix library, this
doesn't need language changes. So a dynamic array library in
Phobos could fulfil most of the possible desires or needs for
strongly typed indexes. But you lose some of the convenience of
the built-in arrays, and you have to import a bulky library that
you are mostly not using.
I see several places in all kinds of D code where strongly typed
indexes can help tell things apart more clearly and safely, but I
think only in some of such situations programmers are willing to
import a numpy-like library just to have strong typing. In D
learn I see that people don't even add "immutable" to the foreach
variable that spans an interval. So I don't expect people to
import numpy just to give types to two indexes of two 1D arrays.
And statistically I think such cases of just two or tree 1D
arrays are much more common than numerical code that manages
several matrices with a good matrix library.
Bye,
bearophile
More information about the Digitalmars-d
mailing list