raz / conform / run / VariantMatch.raz

74 lines · 1.5 KiB · raw · history · last change 7e721e08

1(* match: the names of an arm stand for the fields of the variant
2 itself when it is a variable, and for a copy when it isn't. *)
3module VariantMatch;
4import Out;
5
6type
7 Shape = variant num(n: I64); pair(a, b: I64); none; end;
8 Op = (plus, minus, times, divide);
9
10var g: Shape;
11
12proc copyOfG(): Shape;
13begin
14 return g;
15end;
16
17proc show(s: Shape);
18begin
19 match s of
20 | num(n): Out.str("num "); Out.int(n);
21 | pair(a, b): Out.str("pair "); Out.int(a); Out.char(' '); Out.int(b);
22 | none: Out.str("none");
23 end;
24 Out.ln;
25end;
26
27proc kind(op: Op);
28begin
29 match op of
30 | plus, minus: Out.str("additive");
31 | times: Out.str("times");
32 | else: Out.str("other");
33 end;
34 Out.ln;
35end;
36
37proc size(n: I64);
38begin
39 match n of
40 | 0: Out.str("zero");
41 | 1 .. 9: Out.str("small");
42 | -5 .. -1, 10: Out.str("negative or ten");
43 | else: Out.str("big");
44 end;
45 Out.ln;
46end;
47
48proc main*;
49begin
50 g := pair(3, 4);
51 match g of
52 | pair(a, b): a := a * 10; INC(b); (* through the names: g changes *)
53 | else:
54 end;
55 show(g);
56 match copyOfG() of
57 | pair(a, b): a := 0; b := 0; (* a copy: g does not change *)
58 | else:
59 end;
60 show(g);
61 match g of
62 | num: Out.str("no\n"); (* fields left unnamed *)
63 | pair: Out.str("unnamed\n");
64 | none: Out.str("no\n");
65 end;
66 g := none;
67 show(g);
68 g := num(5);
69 show(g);
70 kind(plus); kind(minus); kind(times); kind(divide);
71 size(0); size(5); size(-3); size(10); size(11);
72end;
73
74end VariantMatch.