April 19, 2005
Georg Wrede wrote:

> If there is a good motivation for if(array[key]) silently inserting the key, then so be it. BUT THEN this should be VERY prominently in the documentation. AND with a proper explanation of the reason this is so.

I think the insertion of missing keys is so it can double as a lvalue:

int[ char[] ] dictionary;

char[] word;

    dictionary[word]++;


Someone mentioned on the thread that talked about the AAs, that it would
be possible to have it insert when used as a lvalue, and not insert when
used as a rvalue. If this could be done, it would clear it up a little ?

Another possibility discussed earlier was throwing an Exception, akin
to comparing something with null. (I thought it should return key.init,
at least when being used as an rvalue - instead of throwing up anything)


I think the "if(array[key])" is just an innocent bystander to all this,
caught in the crossfire. Can't think of any reason to make it insert ?
("array[key];" also inserts, by the way. And still fails to .init, too)

There seems to be at least three different ideas on how it should work:

1)
Have comparisons with null just dereference null (A.V./SEGV/B.E.)
Have retrievals of non-existing keys create and insert them in AA

2)
Have comparisons with null throw Exceptions (call a _d_XXX handler)
Have any non-existing keys throw Exceptions (call a _d_XXX handler)

3)
Define all comparisons with null, as fixed values (true/false)
Return default values (.init) for non-existing keys, no insert

It's a matter of how the operations are defined, in the specification ?
(and I agree that it could use some more explanation and details there)


Note that this is talking about "null == this" and "hash[key]" *only*.

You can still rewrite both of them, as "null is this" or "key in hash".
Neither alternate expression will throw exceptions or create new keys.

Of course, that requires rewriting... (which makes it a porting trap)

--anders


PS.
I'm writing "null == this" here instead of "this == null", since the
latter doesn't always cause such failures in D, just occasionally ?
(and using a form that always does, makes it more clear in the above)

In some languages, they are even defined differently... (e.g. in
Java: "null.equals(this)" throws, but "this.equals(null)" is false)
A main example of a language using the third form 3) would be Perl.
1 2 3
Next ›   Last »