associative arrays: iteration is finally here
Pelle Månsson
pelle.mansson at gmail.com
Wed Oct 28 13:53:36 PDT 2009
Lars T. Kyllingstad wrote:
> Pelle Månsson wrote:
>> Lars T. Kyllingstad wrote:
>>> Pelle Månsson wrote:
>>>> Andrei Alexandrescu wrote:
>>>>> Pelle Månsson wrote:
>>>>>> Also, foreach with a single variable should default to keys, in my
>>>>>> opinion.
>>>>>
>>>>> That is debatable as it would make the same code do different
>>>>> things for e.g. vectors and sparse vectors.
>>>>>
>>>>>
>>>>> Andrei
>>>>
>>>> Debatable indeed, but I find myself using either just the keys or
>>>> the keys and values together, rarely just the values. Maybe that's
>>>> just me.
>>>
>>>
>>> I've used iteration over values more often than iteration over keys.
>>>
>>> Besides, I think consistency is important. Since the default for an
>>> ordinary array is to iterate over the values, it should be the same
>>> for associative arrays.
>>>
>>> -Lars
>> I don't understand this, when do you want the values without the keys?
>> If you do, shouldn't you be using a regular array?
>
> Here's an example:
>
> class SomeObject { ... }
> void doStuffWith(SomeObject s) { ... }
> void doOtherStuffWith(SomeObject s) { ... }
>
> // Make a collection of objects indexed by ID strings.
> SomeObject[string] myObjects;
> ...
>
> // First I just want to do something with one of the
> // objects, namely the one called "foo".
> doStuffWith(myObjects["foo"]);
>
> // Then, I want to do something with all the objects.
> foreach (obj; myObjects) doOtherStuffWith(obj);
>
> Of course, if iteration was over keys instead of values, I'd just write
>
> foreach (id, obj; myObjects) doOtherStuffWith(obj);
>
> But then again, right now, when iteration is over values and I want the
> keys I can just write the same thing. It all comes down to preference,
> and I prefer things the way they are now. :)
>
>
>> Actually, it doesn't matter all that much, as long as we get .keys and
>> .values as alternatives.
>
> I still think the default for foreach should be consistent with normal
> arrays.
>
> -Lars
I think foreach should be consistent with opIn, that is,
if (foo in aa) { //it is in the aa.
foreach (f; aa) { // loop over each item in the aa
//I expect foo to show up in here, since it is "in" the aa.
}
}
I use key iteration more than I use value iteration, and it is what I am
used to. It is, as you say, a matter of preference.
More information about the Digitalmars-d
mailing list