Collections
Smalltalk neophytes only iterate over collections using do:. Veterans make full use of the
Collection enumeration protocol, including
- collect:
- detect:
- detect: ifNone:
- select:
- reject:
- inject: into:
Dictionairies and SequenciableCollections have more enumeration protocol, but this is the
standard Collection enumeration protocol.
Use the collection protocol to
- Make a string consisting of all the capital letters in a string
- Find the minimum character in a string
- Convert a string of alphabetic characters to entirely lowercase.
- Find the first lowercase character in a string.
-
Find the "dollar value" of a string. The dollar value of a string is the sum of the dollar
values of its characters. The dollar value of "a" is 1, of "b" is 2, ..., of "z" is 26, and
all non alphabetic characters are worth 0.
-
Encode a string using the first grade code, which is to replace "a" with "b",
"b" with "c", etc and "z" with "a".
All non alphabetic charcters are unchanged.
Read class Character, especially the "accessing", "converting" and "testing"
protocols.
Class Set is one of the Collection classes, and it implements typical Collection protocol like
do:, add:, remove:, and collect:. However, it doesn't implement typical operations on sets
like interection and union.
Define a union: method that takes a set as an argument and returns a new set that is the
union of the receiver and the argument. Define an intersect: method that returns a new set
that contains only elements that are in both the receiver and the argument.
Here are some operations on Sets that you might want to use:
-
Inherited from Object
-
copy - makes a copy of any object, including a Set
Inherited from Collection
-
addAll: - add all the elements of the argument to the receiver
-
select: - select the subset that cause the block-argument to evaluate true
-
Defined in Set
-
add: - add the argument to the receiver
-
remove: - remove the argument from the receiver
-
do: - evaluate the block that is the argument for each element in the receiver
-
includes: - returns true if the argument is an element of the reciever, else false
Add a protocol 'set operations' to Set, and put your new methods there.
Test your new methods in a workspace by printing expressions like
-
(Set with: 1 with: 2) union: (Set with: 2 with: 3)
-
(Set with: 1 with: 2) intersect: (Set with: 2 with: 3)
What does this do?
-
(1 to: 100) asSet intersect: (90 to: 200 by: 5) asSet