Dynamic array creation with default

bearophile bearophileHUGS at lycos.com
Tue Aug 23 02:23:59 PDT 2011


foobar:

> you raise a valid concern but this looks too complicated.
> I'd suggest to simplify into only two cases.
> 
> // 1) T.INIT - as you suggested the dimension should be checked
> auto foo = new int[][](10, 20); // correct
> auto foo1 = new int[][](10); // compilation error

Keep in mind that currently this is correct and it generates a 1D dynamic array:

auto v = new int[10];


> // 2) function of the array dimension
> auto bar = new int[][](10, 20, (int x, int y) { return x*y; } );
> 
> // if you want a default value just use:
> auto bar1 = new int[][](10, 20, { return 3; } );
> 
> For fixed-sized arrays the function would be CTFE-able.

This is more complex than my suggestions :-)

The most common case is the initialization with a constant value. I'd like this case to be as efficient as possible, so I don't like the { return 3; }. 

The case with a more complex delegate is interesting to initialize constant arrays:

immutable m = new int[][](10, 20, (int x, int y){ return x*y; });

But in my opinion this is not a so common operation. And it's not able to replace Python-style array comps:

foo = [x ** x for x in lazyIterable]

So I don't like your proposals.

Maybe dsimcha will give a Phobos function to allocate & initialize a nD array with a given const value.

Bye,
bearophile


More information about the Digitalmars-d mailing list