Smallthoughts

Thoughts on Smalltalk

OrderedDictionary

I have often wished to create a keyed collection of objects (i.e. a Dictionary) in which the elements could be accessed by key or iterated over in the order in which the elements were added (i.e. treat the collection as either a Dictionary or an OrderedCollection.)

I have seen a few implementations of dictionary classes that retain the insertion order of their elements, but they all seemed to be overly complicated to me. I created this OrderedDictionary by overriding just 5 methods of Dictionary. It remembers the insertion order by maintaining a parallel ordered collection of the associations in an instance variable.

Instances of OrderedDictionary behave as Dictionaries in all respects except that when associations, keys, or values are iterated over, the order in which the iteration occurs is the same as the order in which the associations were originally added to the OrderedDictionary instance.

OrderedDictionary is in Squeaksource

Posted by admin at 15 February 2011, 5:37 am with tags smalltalk, collection link

Comments

Hi Tony,

I often just create it on the fly like this:

    myOrderedDictionary := OrderedCollection new 
add: ('Some Key' -> 'some value');
add: ('whatever' -> 2);
add: (#hello -> [:a | a+1]);
yourself.

Now you can iterate myOrderedDictionary, as it is an OrderedCollection, but you can also ask it for keys and values:

    myOrderedDictionary at: 3 -> #hello -> [:a | a+1]
    (myOrderedDictionary detect: [:e 
e key = #hello]) value -> [:a | a\+1]

It's not strictly a dictionary, but it will work for most of the cases.

Cheers!

Bernat.

Posted by Bernat Romagosa at 15 February 2011, 5:54 am link

Oops Pier messed my code up :(

http://pastie.org/1565960

Posted by Bernat Romagosa at 15 February 2011, 5:57 am link

I cleaned up the comment code.

(A missing feature of Pier is the ability of reviewing a formatted version of your comment before committing it -- or being able to edit one's comment after committing it.) For future reference, I have installed the plug-in that allows you to format Smalltalk code by prefixing each line with ==.

Posted by admin at 5 March 2011, 2:15 pm link