raz / examples / Shapes.raz

39 lines · 876 B · raw · history · last change 2411fde8

1(* Variants and slices: a list of shapes, measured. *)
2module Shapes;
3import Out;
4
5type
6 Shape = variant
7 circle(r: INT);
8 rect(w, h: INT);
9 dot;
10 end;
11
12(* Twice the area, rounded down, of a circle taken as pi = 22/7. *)
13proc area(s: Shape): INT;
14begin
15 match s of
16 | circle(r): return 44 * r * r div 7;
17 | rect(w, h): return 2 * w * h;
18 | dot: return 0;
19 end;
20end;
21
22proc total(shapes: []Shape): INT;
23var i, sum: INT;
24begin
25 sum := 0;
26 for i := 0 to LEN(shapes) - 1 do sum := sum + area(shapes[i]); end;
27 return sum;
28end;
29
30proc main*;
31var shapes: [4]Shape;
32begin
33 shapes := [circle(7), rect(3, 4), dot, rect(1, 1)];
34 Out.str("all: "); Out.int(total(shapes)); Out.ln;
35 Out.str("last two: "); Out.int(total(shapes[2..4])); Out.ln;
36 Out.str("none: "); Out.int(total(shapes[0..0])); Out.ln;
37end;
38
39end Shapes.