Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a collection of associations and a dictionary in Smalltalk?

| dict |
dict := #{'foo'->'brown'. 'bar'->'yellow'.
          'qix'->'white'. 'baz'->'red'. 'flub'->'green'} asDictionary.
dict at: 'qix'

If I PrintIt, I get 'white'. If I remove 'asDictionary', I still get 'white'. What does a dictionary give me that a collection of associations doesn't?

like image 443
Richard Eng Avatar asked Jun 05 '15 13:06

Richard Eng


1 Answers

Expression like #{exp1 . sxp2 . exp3} is amber-smalltalkspecific and creates a HashedCollection, which is a special kind of dictionary where keys are strings (probably in Javascript you use things like this a lot).

In other smalltalks there is no expression like that. Instead array expressions which look like: {exp1 . sxp2 . exp3} (there is no leading #) were introduced in squeak and are also available in pharo (which is a fork of Squeak) and Amber. Now the array expression creates an Array and so you have to use integers for #at: message. For example dict at: 2 will return you an association 'bar'->'yellow' because it is on the second position of the array you've created.

#asDictionary is a method of a collection that converts it into a dictionary given that the elements of the collection are associations. So if you want to create a dictionary with keys other than strings, you can do it like this:

dict := {
    'foo' -> 'brown'  .
        1 -> 'yellow' .
    3 @ 4 -> 'white'  .
   #(1 2) -> 'red' } asDictionary
like image 141
Uko Avatar answered Nov 15 '22 11:11

Uko