Optionally strongly typed array indexes

Mason McGill via Digitalmars-d digitalmars-d at puremagic.com
Wed Jun 4 11:46:03 PDT 2014


On Wednesday, 4 June 2014 at 09:43:20 UTC, bearophile wrote
> 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.

I'll have to check out Ada to get a sense of how this feature 
works and how people use it.

> In D learn I see that people don't even add "immutable" to the 
> foreach variable that spans an interval.

I noticed you did that, though I haven't seen this much on 
Dlang.org. Is this considered idiomatic? Coming mostly from 
JavaScript/Python/CUDA C++ I'm not sure how I feel about the 
terseness/safety trade-off (I can honestly see it both ways).

> 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.

Good point. Though, I don't think adding compiler support for 
strongly typed array dimensions is the full solution. I think 
this is one part of the larger problem of representing units. 
Other languages have solutions to this (I particularly like F#'s: 
http://en.wikibooks.org/wiki/F_Sharp_Programming/Units_of_Measure), 
and it would be very nice to see something this in Phobos:

   /* User code. */
   import std.awesome_unit_library: Unit, of;
   // Unit: defines new types that can be multiplied & divided.
   // of: wraps a container in a stricter version, enforcing units.

   alias Name = Unit!"name";
   alias Food = Unit!"food";
   auto names = ["Fred", "Alice", "Sue"].of!Name;
   auto foods = ["Apple", "Orange", "Tofu"].of!Food;

   foreach (name; ["Bill", "Ted"].of!Name)
   {
       names ~= name; // This compiles happily.
       foods ~= name; // This does not compile, preventing
                      // Bill and Ted from being eaten.
   }


More information about the Digitalmars-d mailing list