The more interesting question

H. S. Teoh hsteoh at quickfur.ath.cx
Wed May 16 10:52:57 PDT 2012


On Wed, May 16, 2012 at 01:36:27PM -0400, Steven Schveighoffer wrote:
> On Wed, 16 May 2012 13:16:36 -0400, H. S. Teoh
> <hsteoh at quickfur.ath.cx> wrote:
> 
> >On Wed, May 16, 2012 at 01:07:54PM -0400, Steven Schveighoffer wrote:
> >[...]
> >>For example:
> >>
> >>auto str = "abcabc";
> >>assert(str[0..3] == str[3..$]); // pass
> >>assert(str[0..3] is str[3..$]); // fail
> >>
> >>which is very counterintuitive.
> >[...]
> >
> >I don't find that counterintuitive at all. To me, 'is' concerns
> >memory identity: are the two things actually one and the same _in
> >memory_? (In this case, no, because they are different chunks of
> >memory that just happens to contain the same values.) Whereas '=='
> >concerns logical identity: do the two things represent the same
> >logical entity? (In this case, yes, these two arrays contain exactly
> >the same elements.)
> >
> >I'd argue that 99% of the time, what you want is logical identity
> >(i.e., ==), not memory identity.
> 
> What's counter intuitive is if you use null as a 'special marker',
> then you use == in most cases, but that one case where you want to
> 'check for the special marker', in which case you *have* to use is.
[...]

It depends upon one's mental model of what an array is.

If you think of an array as a container that exists apart from its
contents, then you'd expect null != [] because null means even the
container itself doesn't exist, whereas [] means the container exists
but contains nothing.

However, if you regard the array simply as the sum total of its
contents, then you'd expect null == [] because there is no container to
speak of, either there are elements, or there are none. When there are
no elements, there is also no array (or equivalently, the array is
empty). Therefore, null and [] are the same thing.

It seems that D takes the latter view, at least as far as == is
concerned. Thus, to distinguish between null and [], one has to bypass
== and use 'is' (i.e., open up the hood of the mental model of an array,
and look into its actual implementation).


T

-- 
Ignorance is bliss... but only until you suffer the consequences!


More information about the Digitalmars-d mailing list