| 1 | (* A generic module with procedure parameters and no library: a table |
| 2 | of sixteen slots, filled by linear probing. *) |
| 3 | module Table(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); |
| 4 | |
| 5 | const Slots = 16; |
| 6 | |
| 7 | type 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. *) |
| 15 | proc put*(t: ^Table; k: K; v: V): BOOL; |
| 16 | var i, n: INT; |
| 17 | begin |
| 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; |
| 33 | end; |
| 34 | |
| 35 | (* What k has; false if it has nothing. *) |
| 36 | proc get*(t: ^Table; k: K): (V, BOOL); |
| 37 | var i, n: INT; zero: V; |
| 38 | begin |
| 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; |
| 46 | end; |
| 47 | |
| 48 | end Table. |