(* Generic modules: counts the words of a text, taken apart by Str.field, in a Map from []const U8 to INT, hashed and compared by Str's procedures, keeps them in order of first sight in a List([]const U8), and prints them with Fmt. *) module Words; import Fmt, Str, Heap, Count := Map([]const U8, INT, Str.hash, Str.eq), Names := List([]const U8); const Text = "the cat and the hat and the bat"; proc main*; var counts: Count.Map; order: Names.List; n: ^Names.Node; k, total: INT; found, _ok: BOOL; w, rest: []const U8; begin Count.init(counts, Heap.heap); Names.init(order, Heap.heap); w, rest := Str.field(Text); while LEN(w) > 0 do INC(total); k, found := Count.get(counts, w); if not found then _ok := Names.push(order, w); end; _ok := Count.put(counts, w, k + 1); w, rest := Str.field(rest); end; Names.reverse(order); n := order.head; while n # nil do k, found := Count.get(counts, n^.val); Fmt.print("{} {}\n", [Fmt.str(n^.val), Fmt.int(k)]); n := n^.next; end; Fmt.print("{} words, {} different\n", [Fmt.int(total), Fmt.int(counts.len)]); end; end Words.