www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Truth value of an empty slice

reply "MrOrdinaire" <mrordinaire gmail.com> writes:
Hi,

I am not sure why the following code would throw a range 
violation whenever haystack does not contain needle.

int[] find(int[] haystack, int needle)
{
     while (haystack && haystack[0] != needle)
         haystack = haystack[1 .. $];
     return haystack;
}

Testing for haystack.length > 0 instead of haystack will make the 
code work.

Does it mean that the truth value of an empty slice depends on 
the underlying array, not on the number of elements the slice 
has, i.e. its length?

Thanks,
Minh
Jan 09 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
MrOrdinaire:

 Does it mean that the truth value of an empty slice depends on 
 the underlying array, not on the number of elements the slice 
 has, i.e. its length?
The short answer is that the safe and readable way to do that in D is to use std.array.empty. Bye, bearophile
Jan 09 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
See also this old ER of mine:

http://d.puremagic.com/issues/show_bug.cgi?id=4733

Bye,
bearophile
Jan 09 2013
parent reply "MrOrdinaire" <mrordinaire gmail.com> writes:
On Wednesday, 9 January 2013 at 13:29:39 UTC, bearophile wrote:
 See also this old ER of mine:

 http://d.puremagic.com/issues/show_bug.cgi?id=4733

 Bye,
 bearophile
Thank you. This clears up the question.
Jan 09 2013
parent "monarch_dodra" <monarchdodra gmail.com> writes:
On Wednesday, 9 January 2013 at 13:38:21 UTC, MrOrdinaire wrote:
 On Wednesday, 9 January 2013 at 13:29:39 UTC, bearophile wrote:
 See also this old ER of mine:

 http://d.puremagic.com/issues/show_bug.cgi?id=4733

 Bye,
 bearophile
Thank you. This clears up the question.
Long story short: the result of "cast(bool)arr" is equivalent to "cast(bool)(arr.ptr)" For example: //---- import std.array; void main() { int[] a; int[] b = [1, 2]; int[] c = b[0 .. 0]; int[] d = b[$ .. $]; assert(!a); //assert(!a.ptr); assert(b); //assert(b.ptr); assert(c); //assert(c.ptr); assert(sameHead(b, c)); assert(sameTail(b, d)); } //----
Jan 09 2013