arrays: if(null == [ ])

Marco Leise Marco.Leise at gmx.de
Wed May 23 19:33:40 PDT 2012


Am Wed, 16 May 2012 09:18:38 -0400
schrieb "Steven Schveighoffer" <schveiguy at yahoo.com>:

> Regardless, we should fix if(!arr) to mean if(!arr.length).
> 
> -Steve

I'm still using 2.057 (GDC). My mental model of D tells me: A reference type's pointer is implicitly converted to bool, when used inside an if-expression.

These are equal statements for any reference type:

	if(reference_type is null)
	if(!(reference_type !is null))
	if(!reference_type)

As an example, I use the these semantics and they feel correct to me. Look at this example where a solution set is expressed as a long[]:

	long[] empty_solution = [];
	assert(empty_solution);     // the solution set is empty (a = a + 42)
	long[] no_solution = null;
	assert(!no_solution);       // a solution is not computable (a = a)

The shortest form is also the most basic one: Do we have a solution set at all?
Once I'm past the 'existence' check, I'd look at the length: if (solution.length == 1) ...
In other use cases you make no distinction between "is null" and "length == 0". For those it is ok to check "if (arr.length)", but I want to make you aware that both cases exist and I think the way it worked in 2.057 was consistent.

Now with 2.059 I have to turn a solution set into a structure with a flag like 'solved'. The language got less expressive here. If that's how it is going too stay then yes, "if(arr)" should really mean "if(arr.length)", because the only time it is not the same is when the language accidentally exposes the implementation detail that an empty string actually needs memory. :)

-- 
Marco



More information about the Digitalmars-d mailing list