raz / conform / run / mods / Table.raz

48 lines · 1.2 KiB · raw · history · last change 51c3b8b8

1(* A generic module with procedure parameters and no library: a table
2 of sixteen slots, filled by linear probing. *)
3module Table(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
4
5const Slots = 16;
6
7type Table* = record
8 used: [Slots]BOOL;
9 keys: [Slots]K;
10 vals: [Slots]V;
11 len*: INT;
12 end;
13
14(* v for k, a new entry or a change; false if the table is full. *)
15proc put*(t: ^Table; k: K; v: V): BOOL;
16var i, n: INT;
17begin
18 i := INT(hash(k) mod Slots);
19 for n := 1 to Slots do
20 if not t^.used[i] then
21 t^.used[i] := true;
22 t^.keys[i] := k;
23 t^.vals[i] := v;
24 INC(t^.len);
25 return true;
26 elsif eq(t^.keys[i], k) then
27 t^.vals[i] := v;
28 return true;
29 end;
30 i := (i + 1) mod Slots;
31 end;
32 return false;
33end;
34
35(* What k has; false if it has nothing. *)
36proc get*(t: ^Table; k: K): (V, BOOL);
37var i, n: INT; zero: V;
38begin
39 i := INT(hash(k) mod Slots);
40 for n := 1 to Slots do
41 if not t^.used[i] then return zero, false; end;
42 if eq(t^.keys[i], k) then return t^.vals[i], true; end;
43 i := (i + 1) mod Slots;
44 end;
45 return zero, false;
46end;
47
48end Table.