string and char[]

Denis Koroskin 2korden at gmail.com
Fri Apr 8 06:40:32 PDT 2011


On Fri, 08 Apr 2011 17:13:19 +0400, Steven Schveighoffer  
<schveiguy at yahoo.com> wrote:

> On Fri, 08 Apr 2011 06:44:42 -0400, Simen kjaeraas  
> <simen.kjaras at gmail.com> wrote:
>
>> On Fri, 08 Apr 2011 12:46:08 +0200, Morlan <home at valentimex.com> wrote:
>>
>>> It is OK if I write
>>>
>>>   int[char[]] asr;
>>>   asr["hello"] = 10;
>>>
>>> but the following does not compile:
>>>
>>>   char[] car = "hello";
>>>
>>> What is the explanation for this behaviour?
>>
>> The first should not be allowed. It is a mistake to use non-immutable
>> keys for an associative array.
>
> int[char[]] asr;
> pragma(msg, typeof(asr).stringof);
>
> outputs:
>
> AssociativeArray!(const(char)[],int)
>
> So the compiler adds const to the keys, which is why it works.
>
> Do I think this is the correct behavior?  Absolutely not.  First, it  
> prevents nothing as far as modifying keys (const accepts mutable keys as  
> well as const and mutable ones).  Second, I believe you should be able  
> to use whatever key constancy you want.  We should just say if you do  
> the wrong thing, it's undefined.  Maybe @safe code can only use  
> immutable keys.  Third, if it must be illegal to have an AA with mutable  
> keys, it should be an error, not silently change to const.
>
> -Steve

What about storing objects as keys? There is nothing wrong to modify those  
objects as long as their order stays the same.
Immutable works, but that's an overkill, tail const would suffice in most  
cases (where an indirection isn't used). E.g.:

int[void*] example;

All that is required is that "int compare(T)(T lhs, T rhs)" is pure (i.e.  
returns same result for same inputs).

In future, compiler could statically enforce that

int compare(void* lhs, void* rhs) pure
{
     if (lhs < rhs) return 1;
     if (lhs > rhs) return -1;
     return 0;
}

is correct and

int compare(char[] lhs, char[] rhs) pure
{
     if (lhs < rhs) return 1;
     if (lhs > rhs) return -1;
     return 0;
}

is not.

For some reason (bug?), both compile with 2.052.


More information about the Digitalmars-d mailing list