raz / examples / Words.raz

35 lines · 1.1 KiB · raw · history · last change e0d008cd

1(* Generic modules: counts the words of a text, taken apart by
2 Str.field, in a Map from []const U8 to INT, hashed and compared by Str's
3 procedures, keeps them in order of
4 first sight in a List([]const U8), and prints them with Fmt. *)
5module Words;
6import Fmt, Str, Heap, Count := Map([]const U8, INT, Str.hash, Str.eq), Names := List([]const U8);
7
8const Text = "the cat and the hat and the bat";
9
10proc main*;
11var
12 counts: Count.Map; order: Names.List; n: ^Names.Node;
13 k, total: INT; found, _ok: BOOL; w, rest: []const U8;
14begin
15 Count.init(counts, Heap.heap);
16 Names.init(order, Heap.heap);
17 w, rest := Str.field(Text);
18 while LEN(w) > 0 do
19 INC(total);
20 k, found := Count.get(counts, w);
21 if not found then _ok := Names.push(order, w); end;
22 _ok := Count.put(counts, w, k + 1);
23 w, rest := Str.field(rest);
24 end;
25 Names.reverse(order);
26 n := order.head;
27 while n # nil do
28 k, found := Count.get(counts, n^.val);
29 Fmt.print("{} {}\n", [Fmt.str(n^.val), Fmt.int(k)]);
30 n := n^.next;
31 end;
32 Fmt.print("{} words, {} different\n", [Fmt.int(total), Fmt.int(counts.len)]);
33end;
34
35end Words.