Set and Bag in Smalltalk
Each element once, or counted every time.
"A Set holds each element once; a Bag counts the repeats."
| customers tally |
customers := Set new.
customers add: 'Alba'; add: 'Bram'; add: 'Alba'.
Transcript show: customers size printString, ' distinct customers'; cr.
tally := Bag new.
tally add: 'broadside'; add: 'chapbook';
add: 'broadside'; add: 'broadside'.
Transcript show: 'Broadsides ordered: ',
(tally occurrencesOf: 'broadside') printString; cr.
tally asSet do: [:job |
Transcript show: job, ' x',
(tally occurrencesOf: job) printString; cr].
How it works
- A
Setswallows duplicates silently. - A
Bagkeeps count:occurrencesOf:reads the tally. asSeton a Bag lists the distinct elements.
Keywords and builtins used here
BagSetTranscriptasSetcrnewprintStringsize
The run, in numbers
- Lines
- 15
- Characters to type
- 508
- Tokens
- 83
- Three-star pace
- 55 tpm
At the three-star pace of 55 tokens a minute, this run takes about 91 seconds.
Step 3 of 4 in Collections, step 12 of 31 in Language basics.