| 1 | title: Lists, arrays, maps and sorting |
| 2 | part: The library |
| 3 | summary: List(T), Vec(T), Map(K, V) and Sort(T), put together in a word-frequency program. |
| 4 | --- |
| 5 | The four generic modules are instantiated like any other generic module, with the types and procedures they need. All four take their memory from an allocator you give them; none of them allocates anything you didn't ask for. |
| 6 | |
| 7 | ## `List(T)` |
| 8 | |
| 9 | A singly linked list with `push` at the front, `pop` from the front, and the nodes exported, so a program walks it itself. Both can fail if the allocator is out of room, and say so. |
| 10 | |
| 11 | ```raz Pile run |
| 12 | module Pile; |
| 13 | import Out, Heap, Ints := List(INT); |
| 14 | |
| 15 | proc main*; |
| 16 | var l: Ints.List; n: ^Ints.Node; v: INT; |
| 17 | begin |
| 18 | Ints.init(l, Heap.heap); |
| 19 | defer Ints.clear(l); |
| 20 | for v := 1 to 5 do _ := Ints.push(l, v * v); end; |
| 21 | Ints.reverse(l); (* oldest first *) |
| 22 | n := l.head; |
| 23 | while n # nil do Out.int(n^.val); Out.char(' '); n := n^.next; end; |
| 24 | Out.ln; |
| 25 | v, _ := Ints.pop(l); |
| 26 | Out.int(v); Out.str(" popped, "); Out.int(l.len); Out.str(" left\n"); |
| 27 | end; |
| 28 | |
| 29 | end Pile. |
| 30 | ``` |
| 31 | |
| 32 | ## `Vec(T)` |
| 33 | |
| 34 | A growable array: one block of elements that doubles when it is full, for what a program learns the length of only as it reads. `push` adds at the end, `add` adds a zero element and gives a pointer to fill it in place, `resize` cuts it short or grows it with zeros. `all` gives the elements as a slice, indexed and checked as any slice is; the slice is good until the array next grows. Running out of memory stops the program, as with `Buf`: an element dropped silently would be wrong data. `room` asks first, for a program that can do better. |
| 35 | |
| 36 | ```raz Squares run |
| 37 | module Squares; |
| 38 | import Out, Heap, Ints := Vec(INT); |
| 39 | |
| 40 | proc main*; |
| 41 | var v: Ints.Vec; i: INT; s: []INT; |
| 42 | begin |
| 43 | Ints.init(v, Heap.heap); |
| 44 | defer Ints.done(v); |
| 45 | for i := 1 to 1000 do Ints.push(v, i * i); end; |
| 46 | s := Ints.all(v); |
| 47 | Out.int(v.len); Out.str(" squares, the last "); Out.int(s[LEN(s) - 1]); Out.ln; |
| 48 | Ints.resize(v, 3); |
| 49 | for i := 0 to v.len - 1 do Out.int(Ints.all(v)[i]); Out.char(' '); end; |
| 50 | Out.ln; |
| 51 | end; |
| 52 | |
| 53 | end Squares. |
| 54 | ``` |
| 55 | |
| 56 | ## `Map(K, V; hash, eq)` |
| 57 | |
| 58 | A hash map. Its key's hash and equality are procedure arguments, so any type can be a key. `put` replaces what a key maps to; `get` says what it maps to and whether it maps to anything; `remove` says whether the key was there. `next` walks the map: from 0, it gives the next entry and the number to pass for the one after, and -1 when there are no more. |
| 59 | |
| 60 | ```raz Ages run |
| 61 | module Ages; |
| 62 | import Out, Fmt, Str, Heap, Book := Map([]const U8, INT, Str.hash, Str.eq); |
| 63 | |
| 64 | proc main*; |
| 65 | var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT; |
| 66 | begin |
| 67 | Book.init(m, Heap.heap); |
| 68 | _ := Book.put(m, "ada", 36); |
| 69 | _ := Book.put(m, "grace", 45); |
| 70 | _ := Book.put(m, "alan", 41); |
| 71 | _ := Book.put(m, "ada", 37); (* replaces *) |
| 72 | age, found := Book.get(m, "ada"); |
| 73 | Fmt.print("ada: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); |
| 74 | age, found := Book.get(m, "linus"); |
| 75 | Fmt.print("linus: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); |
| 76 | ok := Book.remove(m, "alan"); |
| 77 | Fmt.print("{} entries, removed {}\n", [Fmt.int(m.len), Fmt.bool(ok)]); |
| 78 | v := 0; |
| 79 | i, _, age := Book.next(m, 0); |
| 80 | while i >= 0 do |
| 81 | INC(v, age); |
| 82 | i, _, age := Book.next(m, i); |
| 83 | end; |
| 84 | Out.int(v); Out.str(" years in all\n"); |
| 85 | end; |
| 86 | |
| 87 | end Ages. |
| 88 | ``` |
| 89 | |
| 90 | A map's order is its own, so a program that wants an order collects the entries and sorts them, as the next section does. |
| 91 | |
| 92 | ## `Sort(T; less)` |
| 93 | |
| 94 | An in-place sort of a slice, by a `less` procedure, in `n log n` at most and with no memory of its own. Elements equal by `less` may change places. |
| 95 | |
| 96 | ## Putting them together |
| 97 | |
| 98 | Counting words, then listing them by count and then alphabetically: a `Map` for the counts, a `Vec` of records to sort, however many words there are, and `Sort` with a two-level `less`. |
| 99 | |
| 100 | ```raz Freq run |
| 101 | module Freq; |
| 102 | import Fmt, Str, Heap, |
| 103 | Count := Map([]const U8, INT, Str.hash, Str.eq), |
| 104 | Entries := Vec(Entry), |
| 105 | Rank := Sort(Entry, before); |
| 106 | |
| 107 | type Entry = record word: []const U8; n: INT; end; |
| 108 | |
| 109 | const Text = "the cat and the hat and the bat sat on the mat and the cat sat"; |
| 110 | |
| 111 | (* more first; equal counts alphabetically *) |
| 112 | proc before(a, b: Entry): BOOL; |
| 113 | begin |
| 114 | if a.n # b.n then return a.n > b.n; end; |
| 115 | return Str.cmp(a.word, b.word) < 0; |
| 116 | end; |
| 117 | |
| 118 | proc main*; |
| 119 | var |
| 120 | m: Count.Map; entries: Entries.Vec; i, k, found: INT; |
| 121 | w, rest: []const U8; key: []const U8; v: INT; all: []Entry; |
| 122 | begin |
| 123 | Count.init(m, Heap.heap); |
| 124 | defer Count.done(m); |
| 125 | w, rest := Str.field(Text); |
| 126 | while LEN(w) > 0 do |
| 127 | k, _ := Count.get(m, w); |
| 128 | _ := Count.put(m, w, k + 1); |
| 129 | w, rest := Str.field(rest); |
| 130 | end; |
| 131 | Entries.init(entries, Heap.heap); |
| 132 | defer Entries.done(entries); |
| 133 | found, key, v := Count.next(m, 0); |
| 134 | while found >= 0 do |
| 135 | Entries.push(entries, {word: key, n: v}); |
| 136 | found, key, v := Count.next(m, found); |
| 137 | end; |
| 138 | all := Entries.all(entries); |
| 139 | Rank.sort(all); |
| 140 | for i := 0 to LEN(all) - 1 do |
| 141 | Fmt.print("{} {}\n", [Fmt.int(all[i].n), Fmt.str(all[i].word)]); |
| 142 | end; |
| 143 | end; |
| 144 | |
| 145 | end Freq. |
| 146 | ``` |
| 147 | |
| 148 | The keys here are slices of the constant text, so they outlive the map; a program whose keys come from a buffer it will reuse copies them first with `Str.copy`, and gives each back with `Str.free` before `Count.done` gives back the map's own memory. |
| 149 | |
| 150 | ## Choosing |
| 151 | |
| 152 | Use a `List` when you push and pop at one end and walk it in order. Use a `Vec` when you add at the end and index, and don't know how many will come; an array when you do. Use a `Map` when you look things up by key. Use `Sort` on either's slice when you want an order. When none of them fits, they are each under a hundred lines of raz in `lib/`, and the advanced tour's allocator lesson shows what is underneath. |