diff options
Diffstat (limited to 'src/libcore/vec.rs')
| -rw-r--r-- | src/libcore/vec.rs | 28 |
1 files changed, 26 insertions, 2 deletions
diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index e1947b77473..7eba2cbf0cc 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -1744,6 +1744,7 @@ pub fn each_permutation<T:Copy>(v: &[T], put: &fn(ts: &[T]) -> bool) -> bool { * ~~~ * */ +#[cfg(stage0)] pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) { assert!(1u <= n); if n > v.len() { return; } @@ -1751,6 +1752,29 @@ pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) { if !it(v.slice(i, i + n)) { return } } } +/** + * Iterate over all contiguous windows of length `n` of the vector `v`. + * + * # Example + * + * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`, `[3,4]`) + * + * ~~~ + * for windowed(2, &[1,2,3,4]) |v| { + * io::println(fmt!("%?", v)); + * } + * ~~~ + * + */ +#[cfg(not(stage0))] +pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) -> bool { + assert!(1u <= n); + if n > v.len() { return true; } + for uint::range(0, v.len() - n + 1) |i| { + if !it(v.slice(i, i + n)) { return false; } + } + return true; +} /** * Work with the buffer of a vector. @@ -4566,7 +4590,7 @@ mod tests { } i += 0; false - } + }; } #[test] @@ -4581,7 +4605,7 @@ mod tests { } i += 0; false - } + }; } #[test] |
