From 2fab948e01477a9862142993be486bca36aa8152 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Fri, 26 Aug 2011 10:50:02 -0700 Subject: [PATCH] stdlib: Added a treemap traversal function. --- src/lib/treemap.rs | 23 +++++++++++++++++++++++ src/test/stdtest/treemap.rs | 17 +++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/lib/treemap.rs b/src/lib/treemap.rs index 97ab1353c6b..6f73df36ef2 100644 --- a/src/lib/treemap.rs +++ b/src/lib/treemap.rs @@ -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 : &K) -> option { } } } + +// Performs an in-order traversal +fn traverse<@K, @V>(m : &treemap, 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); + } + } + } + } +} diff --git a/src/test/stdtest/treemap.rs b/src/test/stdtest/treemap.rs index 58777b2579c..f77c95fb7f3 100644 --- a/src/test/stdtest/treemap.rs +++ b/src/test/stdtest/treemap.rs @@ -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, _, _)); +} \ No newline at end of file