typestar

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

  1. A Set swallows duplicates silently.
  2. A Bag keeps count: occurrencesOf: reads the tally.
  3. asSet on a Bag lists the distinct elements.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Collections, step 12 of 31 in Language basics.

← Previous Next →