From e56ba156e223e24025a743247610283cca49b30a Mon Sep 17 00:00:00 2001 From: Ben Blum Date: Mon, 25 Jun 2012 18:04:00 -0400 Subject: [PATCH] Add position() to iter/iter-trait --- src/libcore/iter-trait.rs | 3 +++ src/libcore/iter.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/libcore/iter-trait.rs b/src/libcore/iter-trait.rs index 59958e505a4..468bebce4b3 100644 --- a/src/libcore/iter-trait.rs +++ b/src/libcore/iter-trait.rs @@ -16,6 +16,9 @@ fn foldl(+b0: B, blk: fn(B, A) -> B) -> B { } fn contains(x: A) -> bool { iter::contains(self, x) } fn count(x: A) -> uint { iter::count(self, x) } + fn position(f: fn(A) -> bool) -> option { + iter::position(self, f) + } } impl extensions for IMPL_T { diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 8fdc1a28df5..f08fa20fc53 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -85,6 +85,20 @@ fn count>(self: IA, x: A) -> uint { } } +fn position>(self: IA, f: fn(A) -> bool) + -> option { + let mut i = 0; + for self.each {|a| + if f(a) { ret some(i); } + i += 1; + } + ret none; +} + +// note: 'rposition' would only make sense to provide with a bidirectional +// iter interface, such as would provide "reach" in addition to "each". as is, +// it would have to be implemented with foldr, which is too inefficient. + fn repeat(times: uint, blk: fn()) { let mut i = 0u; while i < times {