Skip to content

Commit

Permalink
Develop the associative map example.
Browse files Browse the repository at this point in the history
  • Loading branch information
cpressey committed Feb 25, 2022
1 parent bea6ad2 commit 5e24fbc
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 54 deletions.
68 changes: 51 additions & 17 deletions eg/assoc.castile
Original file line number Diff line number Diff line change
@@ -1,36 +1,70 @@
/*
* Implementation of an associative map in Castile.
*
* The map is implemented as an association list,
* but this fact is hidden from clients, as only
* the operations have access to the internals
* of the struct.
*/

struct assoc {
key: string;
value: string;
next: assoc|void;
} for (singleton, update, lookup, remove)
} for (update, lookup, remove, render)

fun singleton(k: string, v: string) {
make assoc(key:k, value:v, next:null as assoc|void)
fun empty() {
return null as assoc|void
}

fun update(k: string, v: string, a: assoc) {
fun update(k: string, v: string, a: assoc|void) {
make assoc(key:k, value:v, next:a as assoc|void)
}

lookup : assoc, string -> string|void
fun lookup(a: assoc, k: string) {
if a.key == k {
return a.value as string|void
}
n = a.next
typecase n is void {
lookup : assoc|void, string -> string|void
fun lookup(a: assoc|void, k: string) {
typecase a is void {
return null as string|void
}
typecase n is assoc {
return lookup(n, k) as string|void
typecase a is assoc {
if a.key == k {
return a.value as string|void
}
return lookup(a.next, k)
}
}

remove : assoc|void, string -> assoc|void
fun remove(a: assoc|void, k: string) {
typecase a is void {
return a as assoc|void
}
typecase a is assoc {
if a.key == k {
return remove(a.next, k)
}
return make assoc(key:a.key, value:a.value, next:remove(a.next, k)) as assoc|void
}
}

render : assoc|void -> string
fun render(a: assoc|void) {
typecase a is void {
return ""
}
typecase a is assoc {
return concat(a.value, concat(",", render(a.next)))
}
}

fun main() {
a = update("1", "first", update("2", "second", singleton("3", "third")));
r = lookup(a, "2");
print("um");
a = update("3", "third", empty());
a = update("2", "second", a as assoc|void);
a = update("1", "first", a as assoc|void);
print(render(a as assoc|void))
b = remove((a as assoc|void), "2");
print(render(b))
r = lookup(b, "2");
typecase r is void { print("NOT FOUND"); }
typecase r is string { print(r); }
print("ya");
}
37 changes: 0 additions & 37 deletions eg/assoc2.castile

This file was deleted.

0 comments on commit 5e24fbc

Please sign in to comment.