about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPatrick Walton <pcwalton@mimiga.net>2011-07-05 18:29:18 -0700
committerPatrick Walton <pcwalton@mimiga.net>2011-07-05 18:29:47 -0700
commit1bba58504414c845bd6b24b31c3be2d3f982c511 (patch)
treec8eae6ff53ed0cebc966951bcac168e414845ee6
parent2cb129355b93b8f5d932120a2f002fb59d1344fd (diff)
downloadrust-1bba58504414c845bd6b24b31c3be2d3f982c511.tar.gz
rust-1bba58504414c845bd6b24b31c3be2d3f982c511.zip
stdlib: Implement ivec::foldl
-rw-r--r--src/lib/ivec.rs8
-rw-r--r--src/test/run-pass/lib-ivec.rs15
2 files changed, 23 insertions, 0 deletions
diff --git a/src/lib/ivec.rs b/src/lib/ivec.rs
index 14c5dda83b3..a9a5509dae9 100644
--- a/src/lib/ivec.rs
+++ b/src/lib/ivec.rs
@@ -183,6 +183,14 @@ fn filter_map[T,U](fn(&T)->option::t[U] f, &T[mutable?] v) -> U[] {
     ret result;
 }
 
+fn foldl[T,U](fn(&U,&T)->U p, &U z, &T[mutable?] v) -> U {
+    auto sz = len(v);
+    if (sz == 0u) { ret z; }
+    auto first = v.(0);
+    auto rest = slice(v, 1u, sz);
+    ret p(foldl[T,U](p, z, rest), first);
+}
+
 fn any[T](fn(&T)->bool f, &T[] v) -> bool {
     for (T elem in v) { if (f(elem)) { ret true; } }
     ret false;
diff --git a/src/test/run-pass/lib-ivec.rs b/src/test/run-pass/lib-ivec.rs
index 6949e32b5a0..b71a9a545e6 100644
--- a/src/test/run-pass/lib-ivec.rs
+++ b/src/test/run-pass/lib-ivec.rs
@@ -16,6 +16,8 @@ fn square_if_odd(&uint n) -> option::t[uint] {
     ret if (n % 2u == 1u) { some(n * n) } else { none };
 }
 
+fn add(&uint x, &uint y) -> uint { ret x + y; }
+
 fn test_reserve_and_on_heap() {
     let int[] v = ~[ 1, 2 ];
     assert (!ivec::on_heap(v));
@@ -210,6 +212,18 @@ fn test_filter_map() {
     assert (w.(2) == 25u);
 }
 
+fn test_foldl() {
+    // Test on-stack fold.
+    auto v = ~[ 1u, 2u, 3u ];
+    auto sum = ivec::foldl(add, 0u, v);
+    assert (sum == 6u);
+
+    // Test on-heap fold.
+    v = ~[ 1u, 2u, 3u, 4u, 5u ];
+    sum = ivec::foldl(add, 0u, v);
+    assert (sum == 15u);
+}
+
 fn test_any_and_all() {
     assert (ivec::any(is_three, ~[ 1u, 2u, 3u ]));
     assert (!ivec::any(is_three, ~[ 0u, 1u, 2u ]));
@@ -243,6 +257,7 @@ fn main() {
     // Functional utilities
     test_map();
     test_filter_map();
+    test_foldl();
     test_any_and_all();
 }