A Bag is similar to a Set; however, each entry may occur any number of times. One way to implement the class Bag would be to use a dictionary, similar to the way a List was used to implement the class Set in Figure 4.3. The value contained in the dictionary for a given entry would represent the number of times the entry occurs in the bag. The framework for such an implementation is shown below. Change the name of the class from Bag to MyBag, and complete the implementation of class Bag.
Class Bag :Collection
dict count |
[
new
dict $\leftarrow$ Dictionary new
several missing methods
...
first
(count $\leftarrow$ dict first) isNil ifTrue: [ $\uparrow$ nil ].
count $\leftarrow$ count -1 .
$\uparrow$ dict currentKey
next
[count notNil]whileTrue:
$[($ count $>0)$
ifTrue: [count $\leftarrow$ count $-1 . \uparrow$ dict currentKey]
iffalse: [count $\leftarrow$ dict next]].
$\uparrow$ nil
]
Keep in mind that instances of Dictionary respond to first and next with values and not keys. However, the current key is accessible if you use the message currentKey.