• Home
  • Textbooks
  • A little Smalltalk
  • Class Definition

A little Smalltalk

Timothy Budd

Chapter 4

Class Definition - all with Video Answers

Educators


Chapter Questions

Problem 1

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.

Check back soon!

Problem 2

The collections described in Chapter 3 were all linear, meaning they could all be represented by a linearly written list. A common nonlinear data structure in computer science is the binary tree. Implement the class BinaryTree. Instances of BinaryTree contain a left subtree (or nil), a right subtree (or nil), and a value. Instances of the class should respond to the following messages:
left Return the left subtree, usually either nil or other instances of BinaryTree.
left: Set the left subtree to the argument value.
right Return the right subtree.
right: Set the right subtree to the argument value.
value Return the value of the current node.
value: Set the value of the current node to the argument.
How should instances of BinaryTree respond to the enumeration messages first and next? How about print or printString? What should be the superclass of BinaryTree?

Check back soon!