|
0 |
/*
|
|
1 |
* Implementation of an associative map in Castile.
|
|
2 |
*
|
|
3 |
* The map is implemented as an association list,
|
|
4 |
* but this fact is hidden from clients, as only
|
|
5 |
* the operations have access to the internals
|
|
6 |
* of the struct.
|
|
7 |
*/
|
|
8 |
|
0 | 9 |
struct assoc {
|
1 | 10 |
key: string;
|
2 | 11 |
value: string;
|
3 | 12 |
next: assoc|void;
|
4 | |
} for (singleton, update, lookup, remove)
|
|
13 |
} for (update, lookup, remove, render)
|
5 | 14 |
|
6 | |
fun singleton(k: string, v: string) {
|
7 | |
make assoc(key:k, value:v, next:null as assoc|void)
|
|
15 |
fun empty() {
|
|
16 |
return null as assoc|void
|
8 | 17 |
}
|
9 | 18 |
|
10 | |
fun update(k: string, v: string, a: assoc) {
|
|
19 |
fun update(k: string, v: string, a: assoc|void) {
|
11 | 20 |
make assoc(key:k, value:v, next:a as assoc|void)
|
12 | 21 |
}
|
13 | 22 |
|
14 | |
lookup : assoc, string -> string|void
|
15 | |
fun lookup(a: assoc, k: string) {
|
16 | |
if a.key == k {
|
17 | |
return a.value as string|void
|
18 | |
}
|
19 | |
n = a.next
|
20 | |
typecase n is void {
|
|
23 |
lookup : assoc|void, string -> string|void
|
|
24 |
fun lookup(a: assoc|void, k: string) {
|
|
25 |
typecase a is void {
|
21 | 26 |
return null as string|void
|
22 | 27 |
}
|
23 | |
typecase n is assoc {
|
24 | |
return lookup(n, k) as string|void
|
|
28 |
typecase a is assoc {
|
|
29 |
if a.key == k {
|
|
30 |
return a.value as string|void
|
|
31 |
}
|
|
32 |
return lookup(a.next, k)
|
|
33 |
}
|
|
34 |
}
|
|
35 |
|
|
36 |
remove : assoc|void, string -> assoc|void
|
|
37 |
fun remove(a: assoc|void, k: string) {
|
|
38 |
typecase a is void {
|
|
39 |
return a as assoc|void
|
|
40 |
}
|
|
41 |
typecase a is assoc {
|
|
42 |
if a.key == k {
|
|
43 |
return remove(a.next, k)
|
|
44 |
}
|
|
45 |
return make assoc(key:a.key, value:a.value, next:remove(a.next, k)) as assoc|void
|
|
46 |
}
|
|
47 |
}
|
|
48 |
|
|
49 |
render : assoc|void -> string
|
|
50 |
fun render(a: assoc|void) {
|
|
51 |
typecase a is void {
|
|
52 |
return ""
|
|
53 |
}
|
|
54 |
typecase a is assoc {
|
|
55 |
return concat(a.value, concat(",", render(a.next)))
|
25 | 56 |
}
|
26 | 57 |
}
|
27 | 58 |
|
28 | 59 |
fun main() {
|
29 | |
a = update("1", "first", update("2", "second", singleton("3", "third")));
|
30 | |
r = lookup(a, "2");
|
31 | |
print("um");
|
|
60 |
a = update("3", "third", empty());
|
|
61 |
a = update("2", "second", a as assoc|void);
|
|
62 |
a = update("1", "first", a as assoc|void);
|
|
63 |
print(render(a as assoc|void))
|
|
64 |
b = remove((a as assoc|void), "2");
|
|
65 |
print(render(b))
|
|
66 |
r = lookup(b, "2");
|
32 | 67 |
typecase r is void { print("NOT FOUND"); }
|
33 | 68 |
typecase r is string { print(r); }
|
34 | |
print("ya");
|
35 | 69 |
}
|