question about passing associative array to a function
rbutler via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun May 11 08:30:30 PDT 2014
On Sunday, 11 May 2014 at 15:22:29 UTC, John Colvin wrote:
> On Sunday, 11 May 2014 at 14:46:35 UTC, rbutler wrote:
>> I have searched and can not understand something about passing
>> AAs to a function.
>> I have reduced the gist of the question to a tiny program
>> below.
>> If I put "ref" in the function stmt it works, i.e.:
>> ref int[int] aa
>> My confusion is that AAs are supposed to be passed as refs
>> anyway, so I do
>> not understand why I should have to use ref to make it work.
>>
>> Related, it also works if I UN-comment the line d[9] = 9;
>>
>> Thanks for any helpful comments you can make.
>> --rbutler
>>
>> import std.stdio;
>>
>> void test(int[int] aa, int x) {
>> aa[x] = x;
>> aa[8] = 8;
>> }
>>
>> void main() {
>> int[int] d;
>> writeln(d.length);
>> // d[9] = 9;
>> test(d, 0);
>> writeln(d);
>> }
>
> There are problems with the implementation of associative
> arrays. What you are seeing above is a consequence of the
> associative array not being correctly initialised (I think...).
>
> I often create my associative arrays with the following
> function to avoid the problem you're having:
>
> /// Hack to properly initialise an empty AA
> auto initAA(T)()
> {
> T t = [typeof(T.keys[0]).init : typeof(T.values[0]).init];
> t.remove(typeof(T.keys[0]).init);
> return t;
> }
>
> import std.stdio;
>
> void test(int[int] aa, int x) {
> aa[x] = x;
> aa[8] = 8;
> }
>
> void main() {
> int[int] d = initAA!(int[int]);
> test(d, 0);
> writeln(d);
> }
OK. :-)
That makes it difficult to talk about in a classroom, especially
when trying to stress
adherence to the principle of least surprise.
Thanks very much for the quick reply.
More information about the Digitalmars-d-learn
mailing list