Revamping associative arrays

Pelle Månsson pelle.mansson at gmail.com
Wed Oct 21 04:49:01 PDT 2009


Piotrek 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 ;)
> 
>  > 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?
> 
> 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.
> 
> 
> e.g.
> 
> Normal array
> 
> No.       Item
> 0    George
> 1    Fred
> 2    Dany
> 3    Lil
> 
> Index/key is infered from position (offset)
> 
> 
> Now Assoc array:
> 
> No.    Item
> 10    Lindsey
> 21    Romeo
> 1001    C-Jay
> 
> Or
> No.    Item
> first    Europe
> second    South America
> third    Australia
> 
> Or
> Names occurrence frequency:
> 
> No. Item
> Andy    21
> John    23
> Kate    12
> 
> And the only difference is the need for using a hash function for value 
> lookup (calculate position) which should not bother a user when he 
> doesn't care.
> 
> Then when you ask somebody to iterate over the tables, what he will do 
> almost for certain? If it would be me, you know... values all the time. 
> Even for last example most important values are those numbers (despite 
> in this case they're meaningless without keys).
> 
> Cheers
> Piotrek
> 


Put it this way:
  Is there any time you are interested in the values without the keys?
  Is there any time you are interested in the keys without the values?

If you're not interested in the keys, the real question would be why you 
are using an associative array instead of just an array.

I can think of at least one example of when you want key iteration, 
which would be when using a bool[T] as a set.



More information about the Digitalmars-d mailing list