raz / site / content / tour / 06-slices.txt

263 lines · 9.7 KiB · raw · history · last change a5145f64

1title: Arrays, slices and strings
2part: Set
3summary: Five in a row, a window onto them, bytes in UTF-8, raw strings over lines, and checks on every index.
4---
5```raz Slices run
6```
7
8## Arrays
9
10`[5]INT` is an array: five `INT`s in a row, copied when it is assigned or passed. Its length is part of its type, so `[5]INT` and `[6]INT` are different types, and `LEN(a)` of an array is a constant. Array literals are written in brackets, and need a type from the place they are used.
11
12```raz Arrays run
13module Arrays;
14import Out;
15
16proc main*;
17var a, b: [4]INT; grid: [3][3]INT; i, j: INT;
18begin
19 a := [1, 2, 3, 4];
20 b := a; (* a copy *)
21 b[0] := 99;
22 Out.int(a[0]); Out.char(' '); Out.int(b[0]); Out.ln;
23 if a # b then Out.str("they differ now\n"); end;
24
25 for i := 0 to 2 do
26 for j := 0 to 2 do grid[i][j] := i * 3 + j; end;
27 end;
28 Out.int(grid[2][1]); Out.ln; (* 7 *)
29 Out.int(LEN(grid)); Out.char('x'); Out.int(LEN(grid[0])); Out.ln;
30end;
31
32end Arrays.
33```
34
35## Slices
36
37`[]INT` is a slice: a pointer to elements that live elsewhere, and their number, `LEN(s)`. `a[lo..hi]` is the slice of the elements from `lo` up to, but not including, `hi`, and an array goes silently where a slice is wanted. A slice doesn't copy anything: changing an element of it changes the array it looks at.
38
39```raz Windows run
40module Windows;
41import Out;
42
43proc zero(s: []INT);
44var i: INT;
45begin
46 for i := 0 to LEN(s) - 1 do s[i] := 0; end;
47end;
48
49proc show(s: []INT);
50var i: INT;
51begin
52 for i := 0 to LEN(s) - 1 do Out.int(s[i]); Out.char(' '); end;
53 Out.ln;
54end;
55
56proc main*;
57var a: [8]INT; i: INT;
58begin
59 for i := 0 to 7 do a[i] := i + 1; end;
60 zero(a[2..5]); (* a window onto a *)
61 show(a); (* 1 2 0 0 0 6 7 8 *)
62 show(a[6..8]);
63 show(a[3..3]); (* empty: prints just a line feed *)
64end;
65
66end Windows.
67```
68
69Every index and every slice bound is checked, so a slice can never reach past what it was made from; the lesson on failures shows what that looks like.
70
71A slice of a local array is good only while its procedure runs: the array is gone once it returns. So returning one is an error, `return a[0..n]` or `return a` with `a` a local, a value parameter or an array literal. Take the array as a `var` parameter instead, and the slice is of the caller's array; or fill a buffer the caller gives.
72
73## `COPY`
74
75`COPY(d, s)` copies the elements of `s` to the start of `d`, as one block, and is right when they overlap. `LEN(s)` must be at most `LEN(d)`.
76
77```raz Moves run
78module Moves;
79import Out;
80
81proc main*;
82var a: [6]INT; i: INT;
83begin
84 a := [1, 2, 3, 4, 5, 0];
85 COPY(a[1..6], a[0..5]); (* shift everything one place up *)
86 for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end;
87 Out.ln;
88end;
89
90end Moves.
91```
92
93## Strings
94
95A string is a slice of bytes, `[]U8`, in UTF-8, and a string constant is a `[]const U8`: a procedure that only reads a string takes that, and one that writes takes `[]U8`. A `[8]U8` made from one is a copy you can change. Arrays and slices of integers compare with `=` and `#`, so strings do too. `Str` has the rest: ordering, finding, hashing, prefixes and suffixes, trimming, taking apart, ASCII case and kinds of character, UTF-8, and numbers to and from text.
96
97```raz Words run
98module Words;
99import Out, Str;
100
101proc main*;
102var s: []const U8; n: I64; ok: BOOL; name: [8]U8;
103begin
104 s := "hello, world";
105 Out.str(s[7..LEN(s)]); Out.ln;
106 if s[0..5] = "hello" then Out.str("it says hello\n"); end;
107 Out.int(Str.find(s, "world")); Out.ln; (* 7 *)
108 Out.int(Str.find(s, "xyz")); Out.ln; (* -1 *)
109 Out.int(Str.findLast("abcabc", "bc")); Out.ln; (* 4 *)
110 Out.int(Str.findFrom(s, "o", 5)); Out.ln; (* 8: the first o from 5 on *)
111 if Str.isDigit('7') and not Str.isLetter('7') then Out.str("a digit\n"); end;
112 if Str.hasPrefix(s, "hell") then Out.str("prefix\n"); end;
113 if Str.hasSuffix(s, "world") then Out.str("suffix\n"); end;
114 Out.int(Str.cmp("apple", "banana")); Out.ln; (* -1 *)
115 if Str.eqFold("RAZ", "raz") then Out.str("the same, but for case\n"); end;
116 Out.str("["); Out.str(Str.trim(" padded \t\n")); Out.str("]\n");
117
118 n, ok := Str.toInt("-1234");
119 if ok then Out.int(n + 1); Out.ln; end;
120 n, ok := Str.toInt("12x");
121 if not ok then Out.str("not a number\n"); end;
122
123 name := "raz"; (* a copy, the program's own *)
124 name[0] := 'R';
125 Out.str(name[0..3]); Out.ln;
126 Str.upper(name[0..3]); (* in place: name is a variable *)
127 Out.str(name[0..3]); Out.ln;
128end;
129
130end Words.
131```
132
133## Taking a string apart
134
135`Str.cut` splits a string at the first place a separator is: what comes before it, what comes after, and whether it was there at all. `Str.field` gives the first word, past any spaces, and the rest. Neither copies anything: every part is a slice of the string it came from, so taking a line or a file apart costs no memory.
136
137```raz Parts run
138module Parts;
139import Out, Str;
140
141const Text = "name = raz\nkind = language\nyear = 2026\n";
142
143proc main*;
144var line, rest, key, val, w: []const U8; more, ok: BOOL;
145begin
146 (* line by line, then each line at its = *)
147 line, rest, more := Str.cut(Text, "\n");
148 while more do
149 key, val, ok := Str.cut(line, "=");
150 if ok then
151 Out.str(Str.trim(key)); Out.str(" is "); Out.str(Str.trim(val)); Out.ln;
152 end;
153 line, rest, more := Str.cut(rest, "\n");
154 end;
155
156 (* word by word *)
157 w, rest := Str.field(" the quick brown fox ");
158 while LEN(w) > 0 do
159 Out.str("<"); Out.str(w); Out.str(">");
160 w, rest := Str.field(rest);
161 end;
162 Out.ln;
163end;
164
165end Parts.
166```
167
168When `Str.cut` finds no separator it gives the whole string, an empty one and `false`, so the loop above ends after the last line that has a line feed. Building a string goes the other way, in a `Buf`: `Str.join` adds parts with a separator between them, and `Str.replace` adds a string with every match of one text replaced by another (lesson 9 shows `Buf`).
169
170## Raw strings
171
172A string between backquotes is raw: its bytes are the text as it stands, with no escapes, so a backslash or a double quote is itself, and it may run over lines. When the opening backquote ends its line and the closing one has only spaces and tabs before it, those blanks come off the start of every line between, and the text keeps the indent of the code it sits in. Each line ends in a line feed, the last one too.
173
174```raz Raw run
175module Raw;
176import Out;
177
178const Path = `C:\Users\raz\"notes".txt`;
179
180proc usage;
181begin
182 Out.str(`
183 usage: tool [-v] file ...
184 -v say what is done
185 file read this, not standard input
186 `);
187end;
188
189proc main*;
190begin
191 Out.str(Path); Out.ln;
192 usage;
193 Out.str(`a raw string on one line, \n and all`); Out.ln;
194end;
195
196end Raw.
197```
198
199A line of an indented raw string that doesn't start with the closing line's blanks is an error, so a slip in the indent is caught where it is made, not printed. A raw string can't hold a backquote; join one in with `+` and an ordinary string that holds it.
200
201## UTF-8
202
203A character is an `I32`, its code point. A string stays bytes; UTF-8 is how `Str` reads them. `Str.next` walks a string a character at a time, giving each one and where the next starts, -1 at the end. `Str.decode` reads the first character of a string and says how many bytes it took, `Str.decodeLast` the last, and `Str.encode` goes the other way. `Str.chars` counts characters and `Str.valid` says whether a string is UTF-8 at all; a byte that doesn't start a character rightly reads as FFFDH, the character that stands for a wrong one. Byte length and character count are different things, and the program is the one that says which it wants. On a terminal there is a third: a character takes 0, 1 or 2 columns, a combining accent none and an ideograph two, and `Width.columns` counts those.
204
205```raz Runes run
206module Runes;
207import Out, Str, Width;
208
209proc main*;
210var s: []const U8; c: I32; i, size: INT; bytes: [4]U8; k: INT;
211begin
212 s := "caf\u{E9} \u{3BB}";
213 Out.int(LEN(s)); Out.str(" bytes, ");
214 Out.int(Str.chars(s)); Out.str(" characters, ");
215 Out.int(Width.columns("\u{4E2D}\u{6587}")); Out.str(" columns for two ideographs\n");
216
217 (* each character, as its code point *)
218 c, i := Str.next(s, 0);
219 while i >= 0 do
220 Out.int(I64(c)); Out.str(" ");
221 c, i := Str.next(s, i);
222 end;
223 Out.ln;
224
225 c, size := Str.decodeLast(s);
226 Out.int(I64(c)); Out.str(" is last, in "); Out.int(size); Out.str(" bytes\n");
227 bytes, k := Str.encode(955);
228 Out.str(bytes[0..k]); Out.ln;
229 if not Str.valid(s[0..4]) then Out.str("cut in the middle of a character\n"); end;
230end;
231
232end Runes.
233```
234
235`Str` knows UTF-8 and no more of Unicode: its case is ASCII's, and it doesn't say how wide a character is on a terminal or which spellings of a text are the same. Those need tables bigger than the rest of the library.
236
237## Loops over lengths
238
239A `for` loop takes its bounds once, and never steps past the last: with an empty slice, `0 to LEN(s) - 1` doesn't run at all, and the variable can't wrap. `for` takes a constant step with `by`, and `while` and `repeat ... until` do the rest. `break` leaves a loop, and `continue` ends its round: a `for` steps, a `while` or a `repeat` tests again. So a `while` moves on before any `continue`, or it never moves at all.
240
241```raz Loops run
242module Loops;
243import Out;
244
245proc main*;
246var i: INT;
247begin
248 for i := 10 to 0 by -5 do Out.int(i); Out.char(' '); end;
249 Out.ln;
250 i := 1;
251 while i < 100 do i := i * 3; end;
252 Out.int(i); Out.ln;
253 repeat DEC(i, 30); until i < 0;
254 Out.int(i); Out.ln;
255 for i := 1 to 10 do
256 if i mod 3 = 0 then continue; end; (* 3, 6 and 9 passed over *)
257 Out.int(i); Out.char(' ');
258 end;
259 Out.ln;
260end;
261
262end Loops.
263```