word_freq.erl in Erlang
A word-frequency table from lexemes, maps:update_with, one sort.
%% Count word frequencies in a passage and chart the leaders.
passage() ->
"the rain in maine falls mainly on the plain and "
++ "the rain stays on the plain".
main(_) ->
Words = string:lexemes(passage(), " "),
%% Tally into a map; the default arm seeds new words at zero.
Counts = lists:foldl(
fun(W, Acc) -> maps:update_with(W, fun(N) -> N + 1 end, 1, Acc)
end, #{}, Words),
%% Rank: count descending, ties broken by the word itself.
Ranked = lists:sort(
fun({W1, N1}, {W2, N2}) ->
if N1 =/= N2 -> N1 > N2;
true -> W1 =< W2
end
end, maps:to_list(Counts)),
io:format("~p distinct words~n", [length(Ranked)]),
io:format("word ct bar~n"),
[io:format("~-7s ~2B ~s~n", [W, N, lists:duplicate(N, $#)])
|| {W, N} <- Ranked],
ok.
How it works
maps:update_withincrements with a seed for new words.- The sort fun ranks by count with alphabetical ties.
lists:duplicate(N, $#)draws each word's bar.
Keywords and builtins used here
duplicateendfoldlformatfuniflengthlexemesmainpassagesortto_listupdate_with
The run, in numbers
- Lines
- 27
- Characters to type
- 731
- Tokens
- 198
- Three-star pace
- 55 tpm
At the three-star pace of 55 tokens a minute, this run takes about 216 seconds.
Step 1 of 3 in Encore, step 29 of 31 in Language basics.