stdlib: Added a treemap traversal function.
This commit is contained in:
parent
cd913b454d
commit
2fab948e01
@ -15,6 +15,7 @@ export treemap;
|
||||
export init;
|
||||
export insert;
|
||||
export find;
|
||||
export traverse;
|
||||
|
||||
tag tree_node<@K, @V> {
|
||||
empty;
|
||||
@ -74,3 +75,25 @@ fn find<@K, @V>(m : &treemap<K, V>, k : &K) -> option<V> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Performs an in-order traversal
|
||||
fn traverse<@K, @V>(m : &treemap<K, V>, f : fn(&K, &V)) {
|
||||
alt *m {
|
||||
empty. { }
|
||||
node(@k, @v, _, _) {
|
||||
// copy v to make aliases work out
|
||||
let v1 = v;
|
||||
alt *m {
|
||||
node(_, _, left, _) {
|
||||
traverse(left, f);
|
||||
}
|
||||
}
|
||||
f(k, v1);
|
||||
alt *m {
|
||||
node(_, _, _, right) {
|
||||
traverse(right, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -40,3 +40,20 @@ fn find_not_found() {
|
||||
insert(m, 1, 2);
|
||||
assert(find(m, 2) == none);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traverse_in_order() {
|
||||
let m = init();
|
||||
insert(m, 3, ());
|
||||
insert(m, 0, ());
|
||||
insert(m, 4, ());
|
||||
insert(m, 2, ());
|
||||
insert(m, 1, ());
|
||||
|
||||
let n = 0;
|
||||
fn t(n : &mutable int, k : &int, v : &()) {
|
||||
assert(n == k);
|
||||
n += 1;
|
||||
}
|
||||
traverse(m, bind t(n, _, _));
|
||||
}
|
Loading…
Reference in New Issue
Block a user