Set · lesson 6 of 15

Arrays, slices and strings

Slices.raz
module Slices;
import Out, Str;

proc sum(s: []INT): INT;
var i, t: INT;
begin
    t := 0;
    for i := 0 to LEN(s) - 1 do t := t + s[i]; end;
    return t;
end;

proc main*;
var a: [5]INT; i: INT; s, val: []const U8; name: [8]U8; ok: BOOL;
begin
    for i := 0 to 4 do a[i] := i * i; end;
    Out.int(sum(a)); Out.ln;        (* the array, as a slice *)
    Out.int(sum(a[1..3])); Out.ln;  (* a[1] and a[2] *)
    s := "hello, world";
    Out.str(s[7..LEN(s)]); Out.ln;
    if s[0..5] = "hello" then Out.str("it says hello\n"); end;
    Out.int(Str.find(s, "world")); Out.ln;
    _, val, ok := Str.cut(" size = 42 ", "=");
    if ok then Out.str(Str.trim(val)); Out.ln; end;
    name := "raz";                  (* a copy, the program's own *)
    name[0] := 'R';
    Out.str(name[0..3]); Out.ln;
    Out.str(`
        C:\tmp\ "as it stands"
          over lines
        `);
end;

end Slices.
30
5
world
it says hello
7
42
Raz
C:\tmp\ "as it stands"
  over lines

Arrays

[5]INT is an array: five INTs 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.

Arrays.raz
module Arrays;
import Out;

proc main*;
var a, b: [4]INT; grid: [3][3]INT; i, j: INT;
begin
    a := [1, 2, 3, 4];
    b := a;                         (* a copy *)
    b[0] := 99;
    Out.int(a[0]); Out.char(' '); Out.int(b[0]); Out.ln;
    if a # b then Out.str("they differ now\n"); end;

    for i := 0 to 2 do
        for j := 0 to 2 do grid[i][j] := i * 3 + j; end;
    end;
    Out.int(grid[2][1]); Out.ln;    (* 7 *)
    Out.int(LEN(grid)); Out.char('x'); Out.int(LEN(grid[0])); Out.ln;
end;

end Arrays.
1 99
they differ now
7
3x3

Slices

[]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.

Windows.raz
module Windows;
import Out;

proc zero(s: []INT);
var i: INT;
begin
    for i := 0 to LEN(s) - 1 do s[i] := 0; end;
end;

proc show(s: []INT);
var i: INT;
begin
    for i := 0 to LEN(s) - 1 do Out.int(s[i]); Out.char(' '); end;
    Out.ln;
end;

proc main*;
var a: [8]INT; i: INT;
begin
    for i := 0 to 7 do a[i] := i + 1; end;
    zero(a[2..5]);                  (* a window onto a *)
    show(a);                        (* 1 2 0 0 0 6 7 8 *)
    show(a[6..8]);
    show(a[3..3]);                  (* empty: prints just a line feed *)
end;

end Windows.
1 2 0 0 0 6 7 8 
7 8 

Every 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.

A 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.

COPY

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).

Moves.raz
module Moves;
import Out;

proc main*;
var a: [6]INT; i: INT;
begin
    a := [1, 2, 3, 4, 5, 0];
    COPY(a[1..6], a[0..5]);         (* shift everything one place up *)
    for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end;
    Out.ln;
end;

end Moves.
1 1 2 3 4 5 

Strings

A 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.

Words.raz
module Words;
import Out, Str;

proc main*;
var s: []const U8; n: I64; ok: BOOL; name: [8]U8;
begin
    s := "hello, world";
    Out.str(s[7..LEN(s)]); Out.ln;
    if s[0..5] = "hello" then Out.str("it says hello\n"); end;
    Out.int(Str.find(s, "world")); Out.ln;          (* 7 *)
    Out.int(Str.find(s, "xyz")); Out.ln;            (* -1 *)
    Out.int(Str.findLast("abcabc", "bc")); Out.ln;  (* 4 *)
    Out.int(Str.findFrom(s, "o", 5)); Out.ln;       (* 8: the first o from 5 on *)
    if Str.isDigit('7') and not Str.isLetter('7') then Out.str("a digit\n"); end;
    if Str.hasPrefix(s, "hell") then Out.str("prefix\n"); end;
    if Str.hasSuffix(s, "world") then Out.str("suffix\n"); end;
    Out.int(Str.cmp("apple", "banana")); Out.ln;    (* -1 *)
    if Str.eqFold("RAZ", "raz") then Out.str("the same, but for case\n"); end;
    Out.str("["); Out.str(Str.trim("  padded \t\n")); Out.str("]\n");

    n, ok := Str.toInt("-1234");
    if ok then Out.int(n + 1); Out.ln; end;
    n, ok := Str.toInt("12x");
    if not ok then Out.str("not a number\n"); end;

    name := "raz";                  (* a copy, the program's own *)
    name[0] := 'R';
    Out.str(name[0..3]); Out.ln;
    Str.upper(name[0..3]);          (* in place: name is a variable *)
    Out.str(name[0..3]); Out.ln;
end;

end Words.
world
it says hello
7
-1
4
8
a digit
prefix
suffix
-1
the same, but for case
[padded]
-1233
not a number
Raz
RAZ

Taking a string apart

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.

Parts.raz
module Parts;
import Out, Str;

const Text = "name = raz\nkind = language\nyear = 2026\n";

proc main*;
var line, rest, key, val, w: []const U8; more, ok: BOOL;
begin
    (* line by line, then each line at its = *)
    line, rest, more := Str.cut(Text, "\n");
    while more do
        key, val, ok := Str.cut(line, "=");
        if ok then
            Out.str(Str.trim(key)); Out.str(" is "); Out.str(Str.trim(val)); Out.ln;
        end;
        line, rest, more := Str.cut(rest, "\n");
    end;

    (* word by word *)
    w, rest := Str.field("  the quick   brown fox ");
    while LEN(w) > 0 do
        Out.str("<"); Out.str(w); Out.str(">");
        w, rest := Str.field(rest);
    end;
    Out.ln;
end;

end Parts.
name is raz
kind is language
year is 2026
<the><quick><brown><fox>

When 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).

Raw strings

A 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.

Raw.raz
module Raw;
import Out;

const Path = `C:\Users\raz\"notes".txt`;

proc usage;
begin
    Out.str(`
        usage: tool [-v] file ...
          -v    say what is done
          file  read this, not standard input
        `);
end;

proc main*;
begin
    Out.str(Path); Out.ln;
    usage;
    Out.str(`a raw string on one line, \n and all`); Out.ln;
end;

end Raw.
C:\Users\raz\"notes".txt
usage: tool [-v] file ...
  -v    say what is done
  file  read this, not standard input
a raw string on one line, \n and all

A 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.

UTF-8

A 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.

Runes.raz
module Runes;
import Out, Str, Width;

proc main*;
var s: []const U8; c: I32; i, size: INT; bytes: [4]U8; k: INT;
begin
    s := "caf\u{E9} \u{3BB}";
    Out.int(LEN(s)); Out.str(" bytes, ");
    Out.int(Str.chars(s)); Out.str(" characters, ");
    Out.int(Width.columns("\u{4E2D}\u{6587}")); Out.str(" columns for two ideographs\n");

    (* each character, as its code point *)
    c, i := Str.next(s, 0);
    while i >= 0 do
        Out.int(I64(c)); Out.str(" ");
        c, i := Str.next(s, i);
    end;
    Out.ln;

    c, size := Str.decodeLast(s);
    Out.int(I64(c)); Out.str(" is last, in "); Out.int(size); Out.str(" bytes\n");
    bytes, k := Str.encode(955);
    Out.str(bytes[0..k]); Out.ln;
    if not Str.valid(s[0..4]) then Out.str("cut in the middle of a character\n"); end;
end;

end Runes.
8 bytes, 6 characters, 4 columns for two ideographs
99 97 102 233 32 955 
955 is last, in 2 bytes
λ
cut in the middle of a character

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.

Loops over lengths

A 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.

Loops.raz
module Loops;
import Out;

proc main*;
var i: INT;
begin
    for i := 10 to 0 by -5 do Out.int(i); Out.char(' '); end;
    Out.ln;
    i := 1;
    while i < 100 do i := i * 3; end;
    Out.int(i); Out.ln;
    repeat DEC(i, 30); until i < 0;
    Out.int(i); Out.ln;
    for i := 1 to 10 do
        if i mod 3 = 0 then continue; end;     (* 3, 6 and 9 passed over *)
        Out.int(i); Out.char(' ');
    end;
    Out.ln;
end;

end Loops.
10 5 0 
243
-27
1 2 4 5 7 8 10 

Save a program under its module’s name and run it with raz run Name.raz.