raz / conform / run / mods / Pile.raz

36 lines · 737 B · raw · history · last change 51c3b8b8

1(* A generic module that needs no library: a stack of at most eight
2 values of T. *)
3module Pile(T);
4
5const Max = 8;
6
7type Pile* = record
8 items: [Max]T;
9 len*: INT;
10 end;
11
12(* x on top; false if the pile is full. *)
13proc push*(p: ^Pile; x: T): BOOL;
14begin
15 if p^.len = Max then return false; end;
16 p^.items[p^.len] := x;
17 INC(p^.len);
18 return true;
19end;
20
21(* The top, taken off; false if the pile is empty. *)
22proc pop*(p: ^Pile): (T, BOOL);
23var zero: T;
24begin
25 if p^.len = 0 then return zero, false; end;
26 DEC(p^.len);
27 return p^.items[p^.len], true;
28end;
29
30(* The top, left where it is; the pile must not be empty. *)
31proc top*(p: ^Pile): T;
32begin
33 return p^.items[p^.len - 1];
34end;
35
36end Pile.