www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Define .empty property for hashes?

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
Is there a reason why there's no .empty property for hashes? std.array
defines it for arrays, and range types must have it defined. But
hashes are left out even though they define .length. This could be put
in std.array:

 property bool empty(T)(in T a)
    if (isAssociativeArray!T)
{
    return !a.length;
}

I can't mark it as neither pure, nothrow, nor safe. I guess that's an
implementation detail at this point.
Mar 02 2012
next sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 03/02/2012 01:08 PM, Andrej Mitrovic wrote:
 Is there a reason why there's no .empty property for hashes? std.array
 defines it for arrays, and range types must have it defined.

Yes, empty is a part of the InputRange interface. Slices are InputRange ranges but associative arrays are not. Unless they also provide front, which would returns a tuple of key and value I guess, and popFront() which would remove that key and value. But things get interesting again because implementing empty, front, and popFront() on the AA interface would conflate the collection with a range. A better approach might be to continue using byKey() and byValue(), which are ranges and follow the recent proposal of byPair(). (I can't locate the thread for that. (?))
 But
 hashes are left out even though they define .length. This could be put
 in std.array:

  property bool empty(T)(in T a)
      if (isAssociativeArray!T)
 {
      return !a.length;
 }

 I can't mark it as neither pure, nothrow, nor safe. I guess that's an
 implementation detail at this point.

Ali
Mar 02 2012
prev sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Fri, 02 Mar 2012 16:21:00 -0500, Ali =C3=87ehreli <acehreli yahoo.com=
 wrote:

 On 03/02/2012 01:08 PM, Andrej Mitrovic wrote:
  > Is there a reason why there's no .empty property for hashes? std.ar=

  > defines it for arrays, and range types must have it defined.

 Yes, empty is a part of the InputRange interface. Slices are InputRang=

 ranges but associative arrays are not. Unless they also provide front,=

 which would returns a tuple of key and value I guess, and popFront()  =

 which would remove that key and value.

 But things get interesting again because implementing empty, front, an=

 popFront() on the AA interface would conflate the collection with a  =

 range.

Defining .empty for hashes does not make it a range. It could (should) = be defined. Just don't define popFront (which has little meaning anyway). -Steve
Mar 05 2012