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

Timon Gehr timon.gehr at gmx.ch
Thu Jul 4 09:51:29 PDT 2013


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.

>> - 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];
}

It's quite obvious to me what the rules are that govern whether or not 
an empty array is null, but why bother? It's simply not useful. Doing it 
always the same way makes a lot more sense than what's demonstrated 
above. And then, going for non-null empty arrays makes most sense to 
support an efficient implementation of slicing.

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.



More information about the Digitalmars-d mailing list