string and char[]

spir denis.spir at gmail.com
Fri Apr 8 13:12:27 PDT 2011


On 04/08/2011 09:20 PM, Steven Schveighoffer wrote:
> On Fri, 08 Apr 2011 14:57:52 -0400, spir <denis.spir at gmail.com> wrote:
>
>> On 04/08/2011 03:13 PM, Steven Schveighoffer 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.
>>
>> I agree on points 1 & 3. "Second" looks dangerous to me.
>
> Dangerous, yes. But immutable objects are typically not easy to deal with. For
> one, you can't have tail-immutable objects (currently), so implementation of
> such a container is going to be a pain. In fact, dcollections simply doesn't
> work if you have fully immutable types as keys.
>
> In reality, most times you are not using something as a key and somewhere else
> simultaneously. So while theoretically dangerous, it's easy to write code that
> isn't dangerous.

What about ref'ed objects used as keys be compared (at least as keys) by ref -- 
and only by ref.
This is how Lua tables work (and the reason why they're so fast):

a = {1,1} ; b = {2,2}
t = {[a]=1 , [b]=2}
print (t[a], t[{1,1}])  --> 1 nil

a and the second {1,1} key are distinct objects. This is not often what we 
mean, in the general case. Composite objects actually often are, conceptually, 
*values*, like a position or color; thus, should be compared by value.
But they sometimes represent unique "entities", like a game character, which 
should be compared (as keys and everywhere else) by "unicity" -- and only that 
way. Comparing their state simply makes no sense.

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d mailing list