title: Lists, arrays, maps and sorting part: The library summary: List(T), Vec(T), Map(K, V) and Sort(T), put together in a word-frequency program. --- 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. ## `List(T)` 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. ```raz Pile run module Pile; import Out, Heap, Ints := List(INT); proc main*; var l: Ints.List; n: ^Ints.Node; v: INT; begin Ints.init(l, Heap.heap); defer Ints.clear(l); for v := 1 to 5 do _ := Ints.push(l, v * v); end; Ints.reverse(l); (* oldest first *) n := l.head; while n # nil do Out.int(n^.val); Out.char(' '); n := n^.next; end; Out.ln; v, _ := Ints.pop(l); Out.int(v); Out.str(" popped, "); Out.int(l.len); Out.str(" left\n"); end; end Pile. ``` ## `Vec(T)` 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. ```raz Squares run module Squares; import Out, Heap, Ints := Vec(INT); proc main*; var v: Ints.Vec; i: INT; s: []INT; begin Ints.init(v, Heap.heap); defer Ints.done(v); for i := 1 to 1000 do Ints.push(v, i * i); end; s := Ints.all(v); Out.int(v.len); Out.str(" squares, the last "); Out.int(s[LEN(s) - 1]); Out.ln; Ints.resize(v, 3); for i := 0 to v.len - 1 do Out.int(Ints.all(v)[i]); Out.char(' '); end; Out.ln; end; end Squares. ``` ## `Map(K, V; hash, eq)` 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. ```raz Ages run module Ages; import Out, Fmt, Str, Heap, Book := Map([]const U8, INT, Str.hash, Str.eq); proc main*; var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT; begin Book.init(m, Heap.heap); _ := Book.put(m, "ada", 36); _ := Book.put(m, "grace", 45); _ := Book.put(m, "alan", 41); _ := Book.put(m, "ada", 37); (* replaces *) age, found := Book.get(m, "ada"); Fmt.print("ada: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); age, found := Book.get(m, "linus"); Fmt.print("linus: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]); ok := Book.remove(m, "alan"); Fmt.print("{} entries, removed {}\n", [Fmt.int(m.len), Fmt.bool(ok)]); v := 0; i, _, age := Book.next(m, 0); while i >= 0 do INC(v, age); i, _, age := Book.next(m, i); end; Out.int(v); Out.str(" years in all\n"); end; end Ages. ``` 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. ## `Sort(T; less)` 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. ## Putting them together 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`. ```raz Freq run module Freq; import Fmt, Str, Heap, Count := Map([]const U8, INT, Str.hash, Str.eq), Entries := Vec(Entry), Rank := Sort(Entry, before); type Entry = record word: []const U8; n: INT; end; const Text = "the cat and the hat and the bat sat on the mat and the cat sat"; (* more first; equal counts alphabetically *) proc before(a, b: Entry): BOOL; begin if a.n # b.n then return a.n > b.n; end; return Str.cmp(a.word, b.word) < 0; end; proc main*; var m: Count.Map; entries: Entries.Vec; i, k, found: INT; w, rest: []const U8; key: []const U8; v: INT; all: []Entry; begin Count.init(m, Heap.heap); defer Count.done(m); w, rest := Str.field(Text); while LEN(w) > 0 do k, _ := Count.get(m, w); _ := Count.put(m, w, k + 1); w, rest := Str.field(rest); end; Entries.init(entries, Heap.heap); defer Entries.done(entries); found, key, v := Count.next(m, 0); while found >= 0 do Entries.push(entries, {word: key, n: v}); found, key, v := Count.next(m, found); end; all := Entries.all(entries); Rank.sort(all); for i := 0 to LEN(all) - 1 do Fmt.print("{} {}\n", [Fmt.int(all[i].n), Fmt.str(all[i].word)]); end; end; end Freq. ``` 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. ## Choosing 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.