typestar

word_freq.st in Smalltalk

A word-frequency table from a Bag, a sort block, and padding.

"Count word frequencies in a passage and chart the leaders."
| passage counts ranked |
passage := 'the rain in maine falls mainly on the plain and ',
    'the rain stays on the plain'.

"A Bag tallies as it collects."
counts := Bag new.
passage substrings do: [:word | counts add: word].

"Rank the distinct words: count descending, ties alphabetical."
ranked := counts asSet asSortedCollection: [:a :b |
    (counts occurrencesOf: a) = (counts occurrencesOf: b)
        ifTrue: [a < b]
        ifFalse: [(counts occurrencesOf: a)
            > (counts occurrencesOf: b)]].

Transcript show: ranked size printString, ' distinct words'; cr.
Transcript show: 'word    ct bar'; cr.
ranked do: [:word |
    | n |
    n := counts occurrencesOf: word.
    Transcript
        show: (word padRightTo: 7);
        show: (n printString padLeftTo: 3);
        show: ' ';
        show: (String new: n withAll: $#);
        cr].

How it works

  1. A Bag tallies the words as they arrive.
  2. The sort block ranks by count with alphabetical ties.
  3. String new: n withAll: $# draws each bar.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
827
Tokens
135
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 147 seconds.

Type this snippet

Step 1 of 3 in Encore, step 29 of 31 in Language basics.

← Previous Next →