Rust map with predicate
Is there a map-like equivalent in Rust that stops iteration based on a condition I can choose?
I want to iterate over a vector, calling a function on each element as I do, and store the results, but stop repeating if the return value of the function ever satisfies the condition
An example of iterative pseudocode:
results = []
for elem in vec:
result = foo(elem)
if result is None
break
results.push(result)
I can get the clumsy equivalent of this scan by changing the original state, but (AFAIK) it will still iterate over every element
Rusty pseudocode for scan option:
results = vec.iter().scan(false, |fail, elem|
if *fail
return None
result = foo(elem)
if result is None
*fail = true
return result
).collect()
source to share
results = vec.iter().map(foo).take_while(|e| e.is_some()).collect()
Iterators in rust are lazily evaluated. Basically, the call collect
causes each element of the iterator to be evaluated one at a time. This means that once some element fails the predicate in take_while
, no other elements will be read from the original iterator, much less through map
.
source to share
If I read the question correctly, you can use Iterator :: take_while to do this:
results = vec.iter().take_while(|v| foo(v)).collect()
source to share