Set · lesson 8 of 15

Enumerations, sets, variants and match

Shapes.raz
module Shapes;
import Out, Fmt, Math;

type
    Colour = (red, green, blue);
    Colours = set of Colour;
    Shape = variant
        circle(r: F64);
        rect(w, h: F64);
        dot;
    end;

const Some: []Shape = [circle(1.0), rect(2.0, 3.5), dot];

proc area(const s: Shape): F64;
begin
    match s of
    | circle(r): return Math.pi * r * r;
    | rect(w, h): return w * h;
    | dot: return 0.0;
    end;
end;

proc kind(c: I32): []const U8;
begin
    match c of
    | ' ', '\t', '\n': return "space";
    | '0' .. '9': return "digit";
    | 'a' .. 'z', 'A' .. 'Z': return "letter";
    | else: return "other";
    end;
end;

proc colour(name: []const U8): Colour;
begin
    match name of
    | "red", "rose": return red;
    | "green": return green;
    | else: return blue;
    end;
end;

proc main*;
var i: INT; warm: Colours; c: Colour;
begin
    for i := 0 to LEN(Some) - 1 do
        Fmt.print("{}\n", [Fmt.real(area(Some[i]), 2)]);
    end;
    Fmt.print("{} {} {}\n", [Fmt.str(kind('7')), Fmt.str(kind('x')),
        Fmt.str(kind('+'))]);
    warm := {red, blue} - {blue} + {green};
    for c := red to blue do
        if c in warm then Out.int(I64(c)); Out.ln; end;
    end;
    Out.int(I64(colour("rose"))); Out.int(I64(colour("green"))); Out.ln;
end;

end Shapes.
3.14
7.00
0.00
digit letter other
0
1
01

Enumerations

An enumeration is a list of names, in order. They convert to their position and back, and a for loop can run over them. A name may be written with its type, Day.mon, and two enumerations of a module may share a name, Style.bold and Elem.bold, which is then always written so. An integer that has no name at its position is a failed check, never a silent wrong value.

Days.raz
module Days;
import Out;

type Day = (mon, tue, wed, thu, fri, sat, sun);

proc name(d: Day): []const U8;
begin
    match d of
    | mon: return "Monday";
    | tue: return "Tuesday";
    | wed: return "Wednesday";
    | thu: return "Thursday";
    | fri: return "Friday";
    | sat: return "Saturday";
    | sun: return "Sunday";
    end;
end;

proc main*;
var d: Day;
begin
    for d := mon to sun do
        Out.int(I64(d)); Out.str(" "); Out.str(name(d));
        if d >= sat then Out.str(" (weekend)"); end;
        Out.ln;
    end;
    d := Day(4);
    Out.str(name(d)); Out.ln;
end;

end Days.
0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday
5 Saturday (weekend)
6 Sunday (weekend)
Friday

Sets

A set of an enumeration holds any choice of its names, in the bits of a word. in tests membership; + is union, * intersection and - difference; {} is the empty set. Sets are how Unix permissions, option flags and key modifiers are best written.

Perms.raz
module Perms;
import Out;

type
    Perm = (x, w, r);               (* bits 0, 1, 2, as chmod has them *)
    Perms = set of Perm;

proc show(p: Perms);
begin
    if r in p then Out.char('r'); else Out.char('-'); end;
    if w in p then Out.char('w'); else Out.char('-'); end;
    if x in p then Out.char('x'); else Out.char('-'); end;
end;

proc main*;
var user, group, mine: Perms;
begin
    user := {r, w, x};
    group := {r, x};
    show(user); Out.char(' '); show(group); Out.ln;
    show(user * group); Out.char(' ');      (* both: r-x *)
    show(user - group); Out.char(' ');      (* only user: -w- *)
    show(user - {w}); Out.ln;        (* r-x *)
    mine := group;
    if mine = {r, x} then Out.str("same as group\n"); end;
    Out.int(I64(U8(user))); Out.ln;         (* 7: a set is its bits *)
end;

end Perms.
rwx r-x
r-x -w- r-x
same as group
7

Variants

A variant holds one of its cases, each with fields of its own, and match is the only way to read them: it runs the arm of the case the variant holds, naming its fields. Every case has an arm, unless an | else: comes last, so adding a case to the type makes every match that forgot it a compile error.

Tokens.raz
module Tokens;
import Out;

type
    Token = variant
        number(n: INT);
        plus;
        times;
        word(s: []const U8);
    end;

proc describe(t: Token);
begin
    match t of
    | number(n): Out.str("number "); Out.int(n);
    | plus: Out.str("plus");
    | times: Out.str("times");
    | word(s): Out.str("word '"); Out.str(s); Out.char('\'');
    end;
    Out.ln;
end;

(* evaluates tokens in reverse Polish; assumes the input is well formed *)
proc eval(ts: []Token): INT;
var stack: [16]INT; top, i, b: INT;
begin
    top := 0;
    for i := 0 to LEN(ts) - 1 do
        match ts[i] of
        | number(n): stack[top] := n; INC(top);
        | plus: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] + b;
        | times: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] * b;
        | else:
        end;
    end;
    return stack[0];
end;

proc main*;
var ts: [5]Token; i: INT;
begin
    ts := [number(3), number(4), plus, number(5), times];   (* (3 + 4) * 5 *)
    for i := 0 to 4 do describe(ts[i]); end;
    Out.int(eval(ts)); Out.ln;
    describe(word("hello"));
end;

end Tokens.
number 3
number 4
plus
number 5
times
35
word 'hello'

Matching integers

On an integer, match takes constants and ranges, and must have an | else:. Characters are integers, so it is also how a scanner is written.

Classify.raz
module Classify;
import Out;

proc kind(c: I32): []const U8;
begin
    match c of
    | ' ', '\t', '\n': return "space";
    | '0' .. '9': return "digit";
    | 'a' .. 'z', 'A' .. 'Z', '_': return "letter";
    | else: return "other";
    end;
end;

proc main*;
var s: []const U8; i: INT;
begin
    s := "x1 + _y";
    for i := 0 to LEN(s) - 1 do
        Out.char(s[i]); Out.str(" is "); Out.str(kind(I32(s[i]))); Out.ln;
    end;
end;

end Classify.
x is letter
1 is digit
  is space
+ is other
  is space
_ is letter
y is letter

Matching strings

On a string, match takes string constants, several to an arm if need be, and compares them as = does. It too must have an | else:. It is how a program reads a command, an option or a keyword without a chain of elsifs.

Commands.raz
module Commands;
import Out;

type Op = (none, add, sub, show);

proc op(word: []const U8): Op;
begin
    match word of
    | "add", "plus", "+": return add;
    | "sub", "minus", "-": return sub;
    | "show": return show;
    | else: return none;
    end;
end;

proc main*;
var total: INT; words: [6][]const U8; i: INT;
begin
    words := ["add", "plus", "sub", "show", "times", "-"];
    for i := 0 to 5 do
        match op(words[i]) of
        | add: INC(total);
        | sub: DEC(total);
        | show: Out.int(total); Out.ln;
        | none: Out.str(words[i]); Out.str("?\n");
        end;
    end;
    Out.int(total); Out.ln;
end;

end Commands.
1
times?
0

Two labels that are the same string are an error, as two arms for one case are.

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