-
Notifications
You must be signed in to change notification settings - Fork 2
/
Map.m
102 lines (90 loc) · 2.03 KB
/
Map.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
MODULE Map;
IMPORT Std, Vector;
TYPE PAIR* = POINTER TO PairRec;
PairRec= RECORD
key* : Std.OBJECT;
value*: Std.OBJECT
END;
MAP* = POINTER TO MapRec;
MapRec = RECORD
vec : VECTOR;
len : INTEGER
END;
PROCEDURE Pair*(key : Std.OBJECT, value : Std.OBJECT) : PAIR;
VAR p : PAIR;
BEGIN
NEW(p);
p.key := key;
p.value := value;
RETURN p
END Pair;
PROCEDURE Map*() : MAP;
VAR m : MAP;
BEGIN
NEW(m);
m.len := 0;
m.vec = Vector.Vector();
RETURN m
END Map;
PROCEDURE (m: MAP) Clear*();
BEGIN
m.len := 0;
m.vec.Clear()
END Clear;
PROCEDURE (m: MAP) Length*() : INTEGER;
BEGIN
RETURN m.len
END Length;
PROCEDURE (m: MAP) Put*(key: Std.OBJECT; value: Std.OBJECT);
VAR i : INTEGER;
e : Std.OBJECT;
p : PAIR;
BEGIN
FOR i := 0 TO m.len - 1 DO
e := m.vec.At(i);
WITH e: PAIR DO
CASE e.key.CompareTo(key) OF
-1 : (* Continue *)
| 0 : (* Replace *)
e.value := value;
RETURN
| 1 : (* Insert *)
p := Pair(key, value);
m.vec.Insert(i, p);
INC(m.len);
RETURN
END
END
END
END Put;
PROCEDURE (m: MAP) PairAt*(pos: INTEGER) : PAIR;
VAR e : Std.OBJECT;
BEGIN
e := m.vec.At(pos);
RETURN e(PAIR)
END PairAt;
PROCEDURE (m: MAP) Get*(key: Std.OBJECT) : Std.OBJECT;
VAR i : INTEGER;
p : PAIR;
BEGIN
FOR i := 0 TO m.len - 1 DO
p := m.PairAt(i);
CASE p.key.CompareTo(key) DO
-1 : (* Continue *)
| 0 : (* Found *)
RETURN p.value
| 1 : (* Iterated past *)
EXIT
END
END;
RETURN NIL
END Get;
PROCEDURE (m: MAP) KeyAt*(pos: INTEGER) : Std.OBJECT;
BEGIN
RETURN m.PairAt(pos).key
END KeyAt;
PROCEDURE (m: MAP) ValueAt*(pos: INTEGER) : Std.OBJECT;
BEGIN
RETURN m.PairAt(pos).value
END ValueAt;
END Map.