test: Use the new for protocol

This commit is contained in:
Alex Crichton
2013-05-03 16:33:33 -04:00
parent cdc266e47d
commit b05aae2d41
21 changed files with 164 additions and 45 deletions

BIN
src/libcore/core Executable file

Binary file not shown.

View File

@@ -86,9 +86,34 @@ pub fn to_vec<T>(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[T] {
#[cfg(not(stage0))] #[cfg(not(stage0))]
pub fn any<T>(predicate: &fn(T) -> bool, pub fn any<T>(predicate: &fn(T) -> bool,
iter: &fn(f: &fn(T) -> bool) -> bool) -> bool { iter: &fn(f: &fn(T) -> bool) -> bool) -> bool {
// If the predicate returns true, we break. If we ever broke, then we found for iter |x| {
// something if predicate(x) {
!iter(|x| !predicate(x)) return true;
}
}
return false;
}
/**
* Return true if `predicate` is true for all values yielded by an internal iterator.
*
* # Example:
*
* ~~~~
* assert!(all(|&x: &uint| x < 6, |f| uint::range(1, 6, f)));
* assert!(!all(|&x: &uint| x < 5, |f| uint::range(1, 6, f)));
* ~~~~
*/
#[inline(always)]
#[cfg(stage0)]
pub fn all<T>(predicate: &fn(T) -> bool,
iter: &fn(f: &fn(T) -> bool)) -> bool {
for iter |x| {
if !predicate(x) {
return false;
}
}
return true;
} }
/** /**

View File

@@ -3404,7 +3404,7 @@ mod tests {
let lf = ~"\nMary had a little lamb\nLittle lamb\n"; let lf = ~"\nMary had a little lamb\nLittle lamb\n";
let crlf = ~"\r\nMary had a little lamb\r\nLittle lamb\r\n"; let crlf = ~"\r\nMary had a little lamb\r\nLittle lamb\r\n";
fn t(s: &str, f: &fn(&str, &fn(&str) -> bool), u: &[~str]) { fn t(s: &str, f: &fn(&str, &fn(&str) -> bool) -> bool, u: &[~str]) {
let mut v = ~[]; let mut v = ~[];
for f(s) |s| { v.push(s.to_owned()) } for f(s) |s| { v.push(s.to_owned()) }
assert!(vec::all2(v, u, |a,b| a == b)); assert!(vec::all2(v, u, |a,b| a == b));
@@ -3424,7 +3424,7 @@ mod tests {
#[test] #[test]
fn test_words () { fn test_words () {
fn t(s: &str, f: &fn(&str, &fn(&str) -> bool), u: &[~str]) { fn t(s: &str, f: &fn(&str, &fn(&str) -> bool) -> bool, u: &[~str]) {
let mut v = ~[]; let mut v = ~[];
for f(s) |s| { v.push(s.to_owned()) } for f(s) |s| { v.push(s.to_owned()) }
assert!(vec::all2(v, u, |a,b| a == b)); assert!(vec::all2(v, u, |a,b| a == b));

View File

@@ -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) { pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) {
assert!(1u <= n); assert!(1u <= n);
if n > v.len() { return; } 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 } 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. * Work with the buffer of a vector.
@@ -4566,7 +4590,7 @@ mod tests {
} }
i += 0; i += 0;
false false
} };
} }
#[test] #[test]
@@ -4581,7 +4605,7 @@ mod tests {
} }
i += 0; i += 0;
false false
} };
} }
#[test] #[test]

View File

@@ -393,6 +393,7 @@ pub impl<T> DList<T> {
} }
/// Iterate over nodes. /// Iterate over nodes.
#[cfg(stage0)]
fn each_node(@mut self, f: &fn(@mut DListNode<T>) -> bool) { fn each_node(@mut self, f: &fn(@mut DListNode<T>) -> bool) {
let mut link = self.peek_n(); let mut link = self.peek_n();
while link.is_some() { while link.is_some() {
@@ -401,6 +402,17 @@ pub impl<T> DList<T> {
link = nobe.next_link(); link = nobe.next_link();
} }
} }
/// Iterate over nodes.
#[cfg(not(stage0))]
fn each_node(@mut self, f: &fn(@mut DListNode<T>) -> bool) -> bool {
let mut link = self.peek_n();
while link.is_some() {
let nobe = link.get();
if !f(nobe) { return false; }
link = nobe.next_link();
}
return true;
}
/// Check data structure integrity. O(n). /// Check data structure integrity. O(n).
fn assert_consistent(@mut self) { fn assert_consistent(@mut self) {

View File

@@ -256,10 +256,21 @@ impl FileInput {
(line numbers and file names, see documentation for (line numbers and file names, see documentation for
`FileInputState`). Otherwise identical to `lines_each`. `FileInputState`). Otherwise identical to `lines_each`.
*/ */
#[cfg(stage0)]
pub fn each_line_state(&self, pub fn each_line_state(&self,
f: &fn(&str, FileInputState) -> bool) { f: &fn(&str, FileInputState) -> bool) {
self.each_line(|line| f(line, copy self.fi.state)); self.each_line(|line| f(line, copy self.fi.state));
} }
/**
Apply `f` to each line successively, along with some state
(line numbers and file names, see documentation for
`FileInputState`). Otherwise identical to `lines_each`.
*/
#[cfg(not(stage0))]
pub fn each_line_state(&self,
f: &fn(&str, FileInputState) -> bool) -> bool {
self.each_line(|line| f(line, copy self.fi.state))
}
/** /**
@@ -367,10 +378,22 @@ reading from `stdin`).
Fails when attempting to read from a file that can't be opened. Fails when attempting to read from a file that can't be opened.
*/ */
#[cfg(stage0)]
pub fn input(f: &fn(&str) -> bool) { pub fn input(f: &fn(&str) -> bool) {
let mut i = FileInput::from_args(); let mut i = FileInput::from_args();
i.each_line(f); i.each_line(f);
} }
/**
Iterate directly over the command line arguments (no arguments implies
reading from `stdin`).
Fails when attempting to read from a file that can't be opened.
*/
#[cfg(not(stage0))]
pub fn input(f: &fn(&str) -> bool) -> bool {
let mut i = FileInput::from_args();
i.each_line(f)
}
/** /**
Iterate directly over the command line arguments (no arguments Iterate directly over the command line arguments (no arguments
@@ -379,20 +402,44 @@ provided at each call.
Fails when attempting to read from a file that can't be opened. Fails when attempting to read from a file that can't be opened.
*/ */
#[cfg(stage0)]
pub fn input_state(f: &fn(&str, FileInputState) -> bool) { pub fn input_state(f: &fn(&str, FileInputState) -> bool) {
let mut i = FileInput::from_args(); let mut i = FileInput::from_args();
i.each_line_state(f); i.each_line_state(f);
} }
/**
Iterate directly over the command line arguments (no arguments
implies reading from `stdin`) with the current state of the iteration
provided at each call.
Fails when attempting to read from a file that can't be opened.
*/
#[cfg(not(stage0))]
pub fn input_state(f: &fn(&str, FileInputState) -> bool) -> bool {
let mut i = FileInput::from_args();
i.each_line_state(f)
}
/** /**
Iterate over a vector of files (an empty vector implies just `stdin`). Iterate over a vector of files (an empty vector implies just `stdin`).
Fails when attempting to read from a file that can't be opened. Fails when attempting to read from a file that can't be opened.
*/ */
#[cfg(stage0)]
pub fn input_vec(files: ~[Option<Path>], f: &fn(&str) -> bool) { pub fn input_vec(files: ~[Option<Path>], f: &fn(&str) -> bool) {
let mut i = FileInput::from_vec(files); let mut i = FileInput::from_vec(files);
i.each_line(f); i.each_line(f);
} }
/**
Iterate over a vector of files (an empty vector implies just `stdin`).
Fails when attempting to read from a file that can't be opened.
*/
#[cfg(not(stage0))]
pub fn input_vec(files: ~[Option<Path>], f: &fn(&str) -> bool) -> bool {
let mut i = FileInput::from_vec(files);
i.each_line(f)
}
/** /**
Iterate over a vector of files (an empty vector implies just `stdin`) Iterate over a vector of files (an empty vector implies just `stdin`)
@@ -400,11 +447,24 @@ with the current state of the iteration provided at each call.
Fails when attempting to read from a file that can't be opened. Fails when attempting to read from a file that can't be opened.
*/ */
#[cfg(stage0)]
pub fn input_vec_state(files: ~[Option<Path>], pub fn input_vec_state(files: ~[Option<Path>],
f: &fn(&str, FileInputState) -> bool) { f: &fn(&str, FileInputState) -> bool) {
let mut i = FileInput::from_vec(files); let mut i = FileInput::from_vec(files);
i.each_line_state(f); i.each_line_state(f);
} }
/**
Iterate over a vector of files (an empty vector implies just `stdin`)
with the current state of the iteration provided at each call.
Fails when attempting to read from a file that can't be opened.
*/
#[cfg(not(stage0))]
pub fn input_vec_state(files: ~[Option<Path>],
f: &fn(&str, FileInputState) -> bool) -> bool {
let mut i = FileInput::from_vec(files);
i.each_line_state(f)
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {

View File

@@ -674,7 +674,7 @@ impl<T: TotalOrd> Set<T> for TreeSet<T> {
a = x.next(); a = x.next();
} }
} }
return a.each(|&x| f(x)) && y.advance(f); return b.each(|&x| f(x)) && y.advance(f);
} }
} }
@@ -1326,7 +1326,7 @@ mod test_set {
} }
fn check(a: &[int], b: &[int], expected: &[int], fn check(a: &[int], b: &[int], expected: &[int],
f: &fn(&TreeSet<int>, &TreeSet<int>, f: &fn(&int) -> bool)) { f: &fn(&TreeSet<int>, &TreeSet<int>, f: &fn(&int) -> bool) -> bool) {
let mut set_a = TreeSet::new(); let mut set_a = TreeSet::new();
let mut set_b = TreeSet::new(); let mut set_b = TreeSet::new();

View File

@@ -10,8 +10,6 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
#[allow(deprecated_mode)];
/*! /*!
An implementation of the Graph500 Breadth First Search problem in Rust. An implementation of the Graph500 Breadth First Search problem in Rust.
@@ -23,7 +21,7 @@ use std::arc;
use std::time; use std::time;
use std::deque::Deque; use std::deque::Deque;
use std::par; use std::par;
use core::hashmap::{HashMap, HashSet}; use core::hashmap::HashSet;
use core::int::abs; use core::int::abs;
use core::rand::RngUtil; use core::rand::RngUtil;
@@ -83,14 +81,13 @@ fn make_graph(N: uint, edges: ~[(node_id, node_id)]) -> graph {
HashSet::new() HashSet::new()
}; };
do vec::each(edges) |e| { for vec::each(edges) |e| {
match *e { match *e {
(i, j) => { (i, j) => {
graph[i].insert(j); graph[i].insert(j);
graph[j].insert(i); graph[j].insert(i);
} }
} }
true
} }
do vec::map_consume(graph) |mut v| { do vec::map_consume(graph) |mut v| {

View File

@@ -11,4 +11,5 @@
fn main() { fn main() {
fn baz(_x: &fn(y: int) -> int) {} fn baz(_x: &fn(y: int) -> int) {}
for baz |_e| { } //~ ERROR A `for` loop iterator should expect a closure that returns `bool` for baz |_e| { } //~ ERROR A `for` loop iterator should expect a closure that returns `bool`
//~^ ERROR expected `for` closure to return `bool`
} }

View File

@@ -17,7 +17,7 @@
fn borrow(_v: &int) {} fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {} fn borrow_mut(_v: &mut int) {}
fn cond() -> bool { fail!() } fn cond() -> bool { fail!() }
fn for_func(_f: &fn() -> bool) { fail!() } fn for_func(_f: &fn() -> bool) -> bool { fail!() }
fn produce<T>() -> T { fail!(); } fn produce<T>() -> T { fail!(); }
fn inc(v: &mut ~int) { fn inc(v: &mut ~int) {

View File

@@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
fn not_bool(f: &fn(int) -> ~str) {} fn not_bool(f: &fn(int) -> ~str) -> bool {}
fn main() { fn main() {
for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but

View File

@@ -16,10 +16,10 @@ fn uuid_random() -> uint { fail!(); }
fn main() { fn main() {
do uint::range(0, 100000) |_i| { //~ ERROR Do-block body must return bool, but do uint::range(0, 100000) |_i| { //~ ERROR Do-block body must return bool, but
} };
// should get a more general message if the callback // should get a more general message if the callback
// doesn't return nil // doesn't return nil
do uint::range(0, 100000) |_i| { //~ ERROR mismatched types do uint::range(0, 100000) |_i| { //~ ERROR mismatched types
~"str" ~"str"
} };
} }

View File

@@ -9,5 +9,5 @@
// except according to those terms. // except according to those terms.
fn main() { fn main() {
do 5.times {} //~ ERROR Do-block body must return bool, but returns () here. Perhaps do 5.times {}; //~ ERROR Do-block body must return bool, but returns () here. Perhaps
} }

View File

@@ -10,4 +10,5 @@
fn main() { fn main() {
for task::spawn { return true; } //~ ERROR A `for` loop iterator should expect a closure that for task::spawn { return true; } //~ ERROR A `for` loop iterator should expect a closure that
//~^ ERROR expected `for` closure to return `bool`
} }

View File

@@ -18,7 +18,7 @@ mod kitties {
} }
pub impl cat { pub impl cat {
priv fn nap(&self) { uint::range(1u, 10000u, |_i| false)} priv fn nap(&self) { uint::range(1u, 10000u, |_i| false); }
} }
pub fn cat(in_x : uint, in_y : int) -> cat { pub fn cat(in_x : uint, in_y : int) -> cat {

View File

@@ -13,22 +13,18 @@
// it. // it.
trait iterable<A> { trait iterable<A> {
fn iterate(&self, blk: &fn(x: &A) -> bool); fn iterate(&self, blk: &fn(x: &A) -> bool) -> bool;
} }
impl<'self,A> iterable<A> for &'self [A] { impl<'self,A> iterable<A> for &'self [A] {
fn iterate(&self, f: &fn(x: &A) -> bool) { fn iterate(&self, f: &fn(x: &A) -> bool) -> bool {
for vec::each(*self) |e| { vec::each(*self, f)
if !f(e) { break; }
}
} }
} }
impl<A> iterable<A> for ~[A] { impl<A> iterable<A> for ~[A] {
fn iterate(&self, f: &fn(x: &A) -> bool) { fn iterate(&self, f: &fn(x: &A) -> bool) -> bool {
for vec::each(*self) |e| { vec::each(*self, f)
if !f(e) { break; }
}
} }
} }

View File

@@ -18,7 +18,7 @@ fn add_int(x: &mut Ints, v: int) {
x.values <-> values; x.values <-> values;
} }
fn iter_ints(x: &Ints, f: &fn(x: &int) -> bool) { fn iter_ints(x: &Ints, f: &fn(x: &int) -> bool) -> bool {
let l = x.values.len(); let l = x.values.len();
uint::range(0, l, |i| f(&x.values[i])) uint::range(0, l, |i| f(&x.values[i]))
} }

View File

@@ -59,25 +59,26 @@ impl<T> Mutable for cat<T> {
} }
impl<T> Map<int, T> for cat<T> { impl<T> Map<int, T> for cat<T> {
fn each<'a>(&'a self, f: &fn(&int, &'a T) -> bool) { fn each<'a>(&'a self, f: &fn(&int, &'a T) -> bool) -> bool {
let mut n = int::abs(self.meows); let mut n = int::abs(self.meows);
while n > 0 { while n > 0 {
if !f(&n, &self.name) { break; } if !f(&n, &self.name) { return false; }
n -= 1; n -= 1;
} }
return true;
} }
fn contains_key(&self, k: &int) -> bool { *k <= self.meows } fn contains_key(&self, k: &int) -> bool { *k <= self.meows }
fn each_key(&self, f: &fn(v: &int) -> bool) { fn each_key(&self, f: &fn(v: &int) -> bool) -> bool {
for self.each |k, _| { if !f(k) { break; } loop;}; self.each(|k, _| f(k))
} }
fn each_value<'a>(&'a self, f: &fn(v: &'a T) -> bool) { fn each_value<'a>(&'a self, f: &fn(v: &'a T) -> bool) -> bool {
for self.each |_, v| { if !f(v) { break; } loop;}; self.each(|_, v| f(v))
} }
fn mutate_values(&mut self, _f: &fn(&int, &mut T) -> bool) { fn mutate_values(&mut self, _f: &fn(&int, &mut T) -> bool) -> bool {
fail!(~"nope") fail!(~"nope")
} }

View File

@@ -11,14 +11,15 @@
// no-reformat // no-reformat
// Testing various forms of `do` and `for` with empty arg lists // Testing various forms of `do` and `for` with empty arg lists
fn f(f: &fn() -> bool) { fn f(f: &fn() -> bool) -> bool {
true
} }
pub fn main() { pub fn main() {
do f() || { true } do f() || { true };
do f() { true } do f() { true };
do f || { true } do f || { true };
do f { true } do f { true };
for f() || { } for f() || { }
for f() { } for f() { }
for f || { } for f || { }

View File

@@ -10,7 +10,7 @@
// Testing that we can drop the || in for/do exprs // Testing that we can drop the || in for/do exprs
fn f(f: @fn() -> bool) { } fn f(f: @fn() -> bool) -> bool { true }
fn d(f: @fn()) { } fn d(f: @fn()) { }

View File

@@ -12,12 +12,13 @@
use core::cmp::Eq; use core::cmp::Eq;
fn iter<T>(v: ~[T], it: &fn(&T) -> bool) { fn iter<T>(v: ~[T], it: &fn(&T) -> bool) -> bool {
let mut i = 0u, l = v.len(); let mut i = 0u, l = v.len();
while i < l { while i < l {
if !it(&v[i]) { break; } if !it(&v[i]) { return false; }
i += 1u; i += 1u;
} }
return true;
} }
fn find_pos<T:Eq + Copy + Clone>(n: T, h: ~[T]) -> Option<uint> { fn find_pos<T:Eq + Copy + Clone>(n: T, h: ~[T]) -> Option<uint> {