Revamping associative arrays

Bill Baxter wbaxter at gmail.com
Sun Oct 18 16:08:18 PDT 2009


On Sun, Oct 18, 2009 at 3:28 PM, Piotrek <starpit at tlen.pl> wrote:
> Bill Baxter pisze:
>>
>> On Sun, Oct 18, 2009 at 1:12 PM, Piotrek <starpit at tlen.pl> wrote:
>>>
>>> Bill Baxter pisze:
>>>>
>>>> I think the default should be to iterate over whatever 'in' looks at.
>>>>
>>> I was almost convinced, because that rule has a sense. But treating
>>> normal
>>> arrays and associative array has more sense to me.
>>>
>>>
>>> fun (SomeObject object) {
>>> foreach (element;object.arr1){ //normal, but how do I know at first look
>>> //just do something with element
>>> }
>>>
>>> foreach (element;object.arr2){ // assoc, but how do I know at first look
>>> //just do something with element hopefully not index
>>> }
>>
>> That sounds like an argument that there should be no default, because
>> either way it's not clear whether you're iterating over keys or
>> values.
>
>
> Really?! That wasn't my intention :) In both cases I wish it were values ;)

Got that, but we got two explanations for the "most logical behavior".
 I like my explanation, you like yours.  Given that in a sample size
of like 4 here we can't agree, I don't see much hope of there being
overwhelming agreement on the right behavior in the population at
large.  Seems like there's interest in making it harder to make
mistakes with D (see the T[new] discussion), and there's a genuine
ambiguity here so the user should be made to specify what they want.
Otherwise it's easy to make mistakes.  I know I've gotten wrong
before.  To the point where I pretty much always just use the
foreack(k,v; AA) form now just to be sure.  Even if I don't need the
values.  Or the keys or whichever it is ;-)

>> Just get rid of the the one-argument foreach over AAs altogether and force
>> the user to be
>> explicit about it.
>
> I wouldn't do so. Would anybody do an error by thinking that foreach
> (elem,table) should iterate over keys?

Bearophile.  And anyone coming from python, at the least.  And anyone
who agrees with the logic of connecting 'in' with what gets iterated.

> Maybe I'm not thinking correctly but for me an assoc array is just an array
> with additional key (index) features thanks to which I save space and/or
> have more indexing method than only integers.

It can also be thought of as a set with some ancillary data associated
with each element.  In that case the keys are the set elements, and
the values are just some extra stuff hanging off the elements.

--bb



More information about the Digitalmars-d mailing list