[:] as empty associative array literal, plus warning for null

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Jul 4 10:32:26 PDT 2013


On 7/4/13 9:51 AM, Timon Gehr wrote:
> On 07/04/2013 05:51 PM, Andrei Alexandrescu wrote:
>> On 7/4/13 8:27 AM, Timon Gehr wrote:
>>> On 07/04/2013 04:35 PM, Andrei Alexandrescu wrote:
>>>> On 7/4/13 6:32 AM, Steven Schveighoffer wrote:
>>>>> I would not be opposed to a pull request that made [] be non-null, as
>>>>> long as it doesn't allocate.
>>>>
>>>> What would be the benefits?
>>>>
>>>> Andrei
>>>
>>> - Additional sentinel values at basically no cost.
>>
>> OK, an "extra null". These can occasionally useful.
>>
>>> - No accidental flawed relying on empty array is null or empty array !is
>>> null.
>>> (i.e. less nondeterminism.)
>>
>> But null arrays stay, so this doesn't help with that. It may actually
>> add confusion.
>>
>
> It is more likely that 'if(array !is null) { }' is valid under the
> stronger semantics than under the old ones. This removes a potentially
> bug-prone construct, since it is easy to fall into the trap of expecting
> that different syntax denotes a different construct.

Why? Maybe someone returned [] thinking it will be a null array. I don't 
see how adding an obscure "whoa, this is an empty array, but 
surprisingly, it's not null!" marks an increase in clarity.

>>> - One thing less to discuss (this has come up before.)
>>
>> That would be true if e.g. the null array disappeared. As such, this
>> adds yet another type to the discussion.
>> ...
>
> What I mean is that there will be no reason to discuss the following
> atrocity any further:
>
> void main(){ // (Compiles and runs with DMD)
> assert([1].ptr[0..0] !is null);
> assert([1][0..0] is null);
> int i=0;
> assert([1][i..i] !is null);
> assert([] is null);
> auto x=[1];
> assert(x[0..0] !is null);
> auto y=[1][i..i];
> }

Making [] changes exactly one line there if I understand things 
correctly, and does not improve anything much.

> Furthermore let's look at it from a syntactic viewpoint.
>
> Currently we have:
>
> - empty arrays of the form cast(T[])null
> - other empty arrays which are null, eg. []
> - empty arrays which are not null, eg. [1][i..i]
>
> Afterwards we have:
> - empty arrays of the form cast(T[])null
> - empty arrays which are not null, eg. [] or [1][i..i]
>
> IMO that reduces cognitive load, even if not as much as simply getting
> rid of cast(T[])null.

The way I see it is:

- we now have two literals for null arrays
- we also have the ability to create non-null but empty arrays through 
natural reduction and slicing of arrays

The new setup is:

- we'd have one literal for null arrays
- we'd still have the ability to create non-null but empty arrays 
through natural reduction and slicing of arrays
- we'd have Nosferatu in the form of []


Andrei


More information about the Digitalmars-d mailing list