Optionally strongly typed array indexes
Mason McGill via Digitalmars-d
digitalmars-d at puremagic.com
Tue Jun 3 20:15:26 PDT 2014
Interesting idea. I run into these sorts of bugs often doing
multimedia processing. There's definitely a tension between
writing generic code (NumPy-style, operating on abstract
dimensions) and safe code (operating on dimensions with
semantics; OpenCV supports this to an extent). I've never used
Ada so I may be missing the point, but here are my impressions:
It seems to me that the users who may benefit most from this
feature are likely to be using non-built-in data structures. 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 (rather than a list of
lists, boxes of kittens, etc.). I'm inclined to believe use-cases
for strongly-typed indices would often overlap with use-cases for
strongly-typed containers. If that is true, then the language
already provides decent support for annotating indices with
"units":
/* Deep in the belly of some image-processing library... */
alias Row = Dimension!"row";
alias Column = Dimension!"column";
alias Channel = Dimension!"channel";
alias Image = DenseGrid!(ubyte, "row column channel");
/* In user code... */
Image image = drawPrettyPicture();
ubyte r = image[Row(0), Column(0), Channel(0)];
ubyte g = image[Row(0), Column(0), Channel(1)];
ubyte b = image[Row(0), Column(0), Channel(2)];
/* Or if you want to get really fancy... */
enum red = Channel(0), green = Channel(1), blue = Channel(2);
ubyte r = image[Row(0), Column(0), red];
ubyte g = image[Row(0), Column(0), green];
ubyte b = image[Row(0), Column(0), blue];
/* Depending on how DenseGrid.opIndex is defined,
these statements could fail to compile... */
image[Column(0), Row(0), red];
image[blue, Row(0), Column(0)];
Speculation: A good behavior for such a `DenseGrid.opIndex` might
allow untyped (size_t) indices for generic algorithms and users
who can't be bothered, but reject incorrectly-typed indices (e.g.
a `BoxOfKittens` should not be indexed with a `Row`, just as an
`Image` should not be indexed with a `CatName`.
More information about the Digitalmars-d
mailing list