From 1bba58504414c845bd6b24b31c3be2d3f982c511 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Tue, 5 Jul 2011 18:29:18 -0700 Subject: [PATCH] stdlib: Implement ivec::foldl --- src/lib/ivec.rs | 8 ++++++++ src/test/run-pass/lib-ivec.rs | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/lib/ivec.rs b/src/lib/ivec.rs index 14c5dda83b31..a9a5509dae91 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 6949e32b5a0e..b71a9a545e61 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(); }