| 1 | <!doctype html> |
| 2 | <html lang="en"> |
| 3 | <head> |
| 4 | <meta charset="utf-8"> |
| 5 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 6 | <title>Lists, arrays, maps and sorting - More Raz</title> |
| 7 | <meta name="description" content="raz: a small systems language in Wirth's tradition, for x86-64 Linux."> |
| 8 | <meta name="theme-color" content="#E07A5F"> |
| 9 | <meta property="og:title" content="Lists, arrays, maps and sorting - More Raz"> |
| 10 | <meta property="og:description" content="A small systems language for x86-64 Linux. No run time, no GC, one report."> |
| 11 | <meta property="og:image" content="https://raz.lucela.org/social.png"> |
| 12 | <meta name="twitter:card" content="summary_large_image"> |
| 13 | <link rel="icon" href="../favicon.svg" type="image/svg+xml"> |
| 14 | <link rel="icon" href="../favicon-32.png" type="image/png" sizes="32x32"> |
| 15 | <link rel="apple-touch-icon" href="../apple-touch-icon.png"> |
| 16 | <link rel="stylesheet" href="../style.css"> |
| 17 | </head> |
| 18 | <body> |
| 19 | <header><nav><a class="mark" href="../index.html"><img src="../logo.svg" width="26" height="26" alt="">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> |
| 20 | <main> |
| 21 | <div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> |
| 22 | <li><a href="fmt.html">Output and formatting</a></li> |
| 23 | <li><a href="bytes.html">Strings and bytes</a></li> |
| 24 | <li><a href="collections.html" aria-current="page">Lists, arrays, maps and sorting</a></li> |
| 25 | <li><a href="files.html">Files and the command line</a></li> |
| 26 | <li><a href="processes.html">Time, randomness and other programs</a></li> |
| 27 | <li><a href="allocators.html">Writing an allocator</a></li> |
| 28 | </ol> |
| 29 | <h3>Standing alone</h3><ol start='7'> |
| 30 | <li><a href="static.html">A program with no run time</a></li> |
| 31 | <li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> |
| 32 | <li><a href="lifecycle.html">Starting, ending, and signals</a></li> |
| 33 | <li><a href="targets.html">One module, one file per target</a></li> |
| 34 | </ol> |
| 35 | <h3>The machine</h3><ol start='11'> |
| 36 | <li><a href="asm.html">Procedures in assembly</a></li> |
| 37 | <li><a href="syscalls.html">System calls</a></li> |
| 38 | <li><a href="listing.html">What the compiler makes</a></li> |
| 39 | </ol> |
| 40 | <h3>Shared memory</h3><ol start='14'> |
| 41 | <li><a href="volatile.html">Volatile</a></li> |
| 42 | <li><a href="atomics.html">Atomics</a></li> |
| 43 | <li><a href="ordering.html">Ordering and publication</a></li> |
| 44 | <li><a href="lockfree.html">A lock-free stack</a></li> |
| 45 | <li><a href="ring.html">A ring buffer between threads</a></li> |
| 46 | </ol></aside><article><p class="kicker">The library · lesson 3 of 18</p><h1>Lists, arrays, maps and sorting</h1> |
| 47 | <p>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.</p> |
| 48 | <h2><code>List(T)</code></h2> |
| 49 | <p>A singly linked list with <code>push</code> at the front, <code>pop</code> 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.</p> |
| 50 | <div class="file"><span>Pile.raz</span></div><pre class="code"><code><span class="kw">module</span> Pile; |
| 51 | <span class="kw">import</span> Out, Heap, Ints := List(<span class="ty">INT</span>); |
| 52 | |
| 53 | <span class="kw">proc</span> main*; |
| 54 | <span class="kw">var</span> l: Ints.List; n: ^Ints.Node; v: <span class="ty">INT</span>; |
| 55 | <span class="kw">begin</span> |
| 56 | Ints.init(l, Heap.heap); |
| 57 | <span class="kw">defer</span> Ints.clear(l); |
| 58 | <span class="kw">for</span> v := <span class="number">1</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> _ := Ints.push(l, v * v); <span class="kw">end</span>; |
| 59 | Ints.reverse(l); <span class="comment">(* oldest first *)</span> |
| 60 | n := l.head; |
| 61 | <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> Out.int(n^.val); Out.char(<span class="string">' '</span>); n := n^.next; <span class="kw">end</span>; |
| 62 | Out.ln; |
| 63 | v, _ := Ints.pop(l); |
| 64 | Out.int(v); Out.str(<span class="string">" popped, "</span>); Out.int(l.len); Out.str(<span class="string">" left\n"</span>); |
| 65 | <span class="kw">end</span>; |
| 66 | |
| 67 | <span class="kw">end</span> Pile.</code></pre> |
| 68 | <pre class="output"><code>1 4 9 16 25 |
| 69 | 1 popped, 4 left |
| 70 | </code></pre> |
| 71 | <h2><code>Vec(T)</code></h2> |
| 72 | <p>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. <code>push</code> adds at the end, <code>add</code> adds a zero element and gives a pointer to fill it in place, <code>resize</code> cuts it short or grows it with zeros. <code>all</code> 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 <code>Buf</code>: an element dropped silently would be wrong data. <code>room</code> asks first, for a program that can do better.</p> |
| 73 | <div class="file"><span>Squares.raz</span></div><pre class="code"><code><span class="kw">module</span> Squares; |
| 74 | <span class="kw">import</span> Out, Heap, Ints := Vec(<span class="ty">INT</span>); |
| 75 | |
| 76 | <span class="kw">proc</span> main*; |
| 77 | <span class="kw">var</span> v: Ints.Vec; i: <span class="ty">INT</span>; s: []<span class="ty">INT</span>; |
| 78 | <span class="kw">begin</span> |
| 79 | Ints.init(v, Heap.heap); |
| 80 | <span class="kw">defer</span> Ints.done(v); |
| 81 | <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">1000</span> <span class="kw">do</span> Ints.push(v, i * i); <span class="kw">end</span>; |
| 82 | s := Ints.all(v); |
| 83 | Out.int(v.len); Out.str(<span class="string">" squares, the last "</span>); Out.int(s[<span class="ty">LEN</span>(s) - <span class="number">1</span>]); Out.ln; |
| 84 | Ints.resize(v, <span class="number">3</span>); |
| 85 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> v.len - <span class="number">1</span> <span class="kw">do</span> Out.int(Ints.all(v)[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; |
| 86 | Out.ln; |
| 87 | <span class="kw">end</span>; |
| 88 | |
| 89 | <span class="kw">end</span> Squares.</code></pre> |
| 90 | <pre class="output"><code>1000 squares, the last 1000000 |
| 91 | 1 4 9 |
| 92 | </code></pre> |
| 93 | <h2><code>Map(K, V; hash, eq)</code></h2> |
| 94 | <p>A hash map. Its key's hash and equality are procedure arguments, so any type can be a key. <code>put</code> replaces what a key maps to; <code>get</code> says what it maps to and whether it maps to anything; <code>remove</code> says whether the key was there. <code>next</code> 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.</p> |
| 95 | <div class="file"><span>Ages.raz</span></div><pre class="code"><code><span class="kw">module</span> Ages; |
| 96 | <span class="kw">import</span> Out, Fmt, Str, Heap, Book := Map([]<span class="kw">const</span> <span class="ty">U8</span>, <span class="ty">INT</span>, Str.hash, Str.eq); |
| 97 | |
| 98 | <span class="kw">proc</span> main*; |
| 99 | <span class="kw">var</span> m: Book.Map; age: <span class="ty">INT</span>; found, ok: <span class="ty">BOOL</span>; i: <span class="ty">INT</span>; v: <span class="ty">INT</span>; |
| 100 | <span class="kw">begin</span> |
| 101 | Book.init(m, Heap.heap); |
| 102 | _ := Book.put(m, <span class="string">"ada"</span>, <span class="number">36</span>); |
| 103 | _ := Book.put(m, <span class="string">"grace"</span>, <span class="number">45</span>); |
| 104 | _ := Book.put(m, <span class="string">"alan"</span>, <span class="number">41</span>); |
| 105 | _ := Book.put(m, <span class="string">"ada"</span>, <span class="number">37</span>); <span class="comment">(* replaces *)</span> |
| 106 | age, found := Book.get(m, <span class="string">"ada"</span>); |
| 107 | Fmt.print(<span class="string">"ada: {} ({})\n"</span>, [Fmt.int(age), Fmt.bool(found)]); |
| 108 | age, found := Book.get(m, <span class="string">"linus"</span>); |
| 109 | Fmt.print(<span class="string">"linus: {} ({})\n"</span>, [Fmt.int(age), Fmt.bool(found)]); |
| 110 | ok := Book.remove(m, <span class="string">"alan"</span>); |
| 111 | Fmt.print(<span class="string">"{} entries, removed {}\n"</span>, [Fmt.int(m.len), Fmt.bool(ok)]); |
| 112 | v := <span class="number">0</span>; |
| 113 | i, _, age := Book.next(m, <span class="number">0</span>); |
| 114 | <span class="kw">while</span> i >= <span class="number">0</span> <span class="kw">do</span> |
| 115 | <span class="ty">INC</span>(v, age); |
| 116 | i, _, age := Book.next(m, i); |
| 117 | <span class="kw">end</span>; |
| 118 | Out.int(v); Out.str(<span class="string">" years in all\n"</span>); |
| 119 | <span class="kw">end</span>; |
| 120 | |
| 121 | <span class="kw">end</span> Ages.</code></pre> |
| 122 | <pre class="output"><code>ada: 37 (true) |
| 123 | linus: 0 (false) |
| 124 | 2 entries, removed true |
| 125 | 82 years in all |
| 126 | </code></pre> |
| 127 | <p>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.</p> |
| 128 | <h2><code>Sort(T; less)</code></h2> |
| 129 | <p>An in-place sort of a slice, by a <code>less</code> procedure, in <code>n log n</code> at most and with no memory of its own. Elements equal by <code>less</code> may change places.</p> |
| 130 | <h2>Putting them together</h2> |
| 131 | <p>Counting words, then listing them by count and then alphabetically: a <code>Map</code> for the counts, a <code>Vec</code> of records to sort, however many words there are, and <code>Sort</code> with a two-level <code>less</code>.</p> |
| 132 | <div class="file"><span>Freq.raz</span></div><pre class="code"><code><span class="kw">module</span> Freq; |
| 133 | <span class="kw">import</span> Fmt, Str, Heap, |
| 134 | Count := Map([]<span class="kw">const</span> <span class="ty">U8</span>, <span class="ty">INT</span>, Str.hash, Str.eq), |
| 135 | Entries := Vec(Entry), |
| 136 | Rank := Sort(Entry, before); |
| 137 | |
| 138 | <span class="kw">type</span> Entry = <span class="kw">record</span> word: []<span class="kw">const</span> <span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>; |
| 139 | |
| 140 | <span class="kw">const</span> Text = <span class="string">"the cat and the hat and the bat sat on the mat and the cat sat"</span>; |
| 141 | |
| 142 | <span class="comment">(* more first; equal counts alphabetically *)</span> |
| 143 | <span class="kw">proc</span> before(a, b: Entry): <span class="ty">BOOL</span>; |
| 144 | <span class="kw">begin</span> |
| 145 | <span class="kw">if</span> a.n # b.n <span class="kw">then</span> <span class="kw">return</span> a.n > b.n; <span class="kw">end</span>; |
| 146 | <span class="kw">return</span> Str.cmp(a.word, b.word) < <span class="number">0</span>; |
| 147 | <span class="kw">end</span>; |
| 148 | |
| 149 | <span class="kw">proc</span> main*; |
| 150 | <span class="kw">var</span> |
| 151 | m: Count.Map; entries: Entries.Vec; i, k, found: <span class="ty">INT</span>; |
| 152 | w, rest: []<span class="kw">const</span> <span class="ty">U8</span>; key: []<span class="kw">const</span> <span class="ty">U8</span>; v: <span class="ty">INT</span>; all: []Entry; |
| 153 | <span class="kw">begin</span> |
| 154 | Count.init(m, Heap.heap); |
| 155 | <span class="kw">defer</span> Count.done(m); |
| 156 | w, rest := Str.field(Text); |
| 157 | <span class="kw">while</span> <span class="ty">LEN</span>(w) > <span class="number">0</span> <span class="kw">do</span> |
| 158 | k, _ := Count.get(m, w); |
| 159 | _ := Count.put(m, w, k + <span class="number">1</span>); |
| 160 | w, rest := Str.field(rest); |
| 161 | <span class="kw">end</span>; |
| 162 | Entries.init(entries, Heap.heap); |
| 163 | <span class="kw">defer</span> Entries.done(entries); |
| 164 | found, key, v := Count.next(m, <span class="number">0</span>); |
| 165 | <span class="kw">while</span> found >= <span class="number">0</span> <span class="kw">do</span> |
| 166 | Entries.push(entries, {word: key, n: v}); |
| 167 | found, key, v := Count.next(m, found); |
| 168 | <span class="kw">end</span>; |
| 169 | all := Entries.all(entries); |
| 170 | Rank.sort(all); |
| 171 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(all) - <span class="number">1</span> <span class="kw">do</span> |
| 172 | Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.int(all[i].n), Fmt.str(all[i].word)]); |
| 173 | <span class="kw">end</span>; |
| 174 | <span class="kw">end</span>; |
| 175 | |
| 176 | <span class="kw">end</span> Freq.</code></pre> |
| 177 | <pre class="output"><code>5 the |
| 178 | 3 and |
| 179 | 2 cat |
| 180 | 2 sat |
| 181 | 1 bat |
| 182 | 1 hat |
| 183 | 1 mat |
| 184 | 1 on |
| 185 | </code></pre> |
| 186 | <p>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 <code>Str.copy</code>, and gives each back with <code>Str.free</code> before <code>Count.done</code> gives back the map's own memory.</p> |
| 187 | <h2>Choosing</h2> |
| 188 | <p>Use a <code>List</code> when you push and pop at one end and walk it in order. Use a <code>Vec</code> when you add at the end and index, and don't know how many will come; an array when you do. Use a <code>Map</code> when you look things up by key. Use <code>Sort</code> on either's slice when you want an order. When none of them fits, they are each under a hundred lines of raz in <code>lib/</code>, and the advanced tour's allocator lesson shows what is underneath.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="bytes.html">← Strings and bytes</a><a href="index.html">Contents</a><a class="next" href="files.html">Files and the command line →</a></div></article></div> |
| 189 | </main> |
| 190 | <footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> |
| 191 | </body> |
| 192 | </html> |