Thread overview
Truth value of an empty slice
Jan 09, 2013
MrOrdinaire
Jan 09, 2013
bearophile
Jan 09, 2013
bearophile
Jan 09, 2013
MrOrdinaire
Jan 09, 2013
monarch_dodra
January 09, 2013
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
January 09, 2013
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
January 09, 2013
See also this old ER of mine:

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

Bye,
bearophile
January 09, 2013
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.
January 09, 2013
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));
}
//----