Bert Freudenberg wrote:


Am 23.08.2006 um 21:15 schrieb cdrick:

Hi all -

not an important question here, more a discussion. I was wondering
which method is the more appropriate (nice and/or efficient) to
enumerate all the elements of a collection and the index of each
elements...


(a) ---- à la C

(1 to: collection size) do: [:index |
                        html render: 'Victime ', index printString.
                                               html render:
collection at: index]

(b) --- indexOf

collection do: [:victim |
html render: 'Victime ', (collection indexOf: victim) printString.
                                               html render: victim]

(c) ---- keysAndValuesDo:

collection keysAndValuesDo: [:index :victim |
                        html render: index printString.
                                               html render: member]

(d) ---- using a local var

| index |
index := 0.
collection do: [:victim | index := index + 1.
                        html render: 'Victime ', index printString.
                                               html render: victim]

What solution would you suggest ?
I think we forget (a) and (d)
I like (c) but maybe (b) is more readable ?

Maybe there is another way ?

(c), though I like #withIndexDo: better since it mimics the #with:do: pattern.

I would vote for #withIndexDo: too which has in 'intention revealing name' :-)

And, please forget about (b), this is way too slow and wrong.

Slow because the complexity jump from O(n) to O(n²). Remember that #indexOf: has to search for the element in all the collection.

Wrong because:

collection := #($a $b $a).
collection
  do: [:each | Transcript
                 show: (collection indexOf: each);
                 space]

Will print '1 2 1' instead of '1 2 3'. Index answered by #indexOf: if the first index on which the object is found.


Bye
_______________________________________________
Beginners mailing list
Beginners@lists.squeakfoundation.org
http://lists.squeakfoundation.org/mailman/listinfo/beginners

Reply via email to