Rust map with predicate

functional-programming, rust

Solution

results = vec.iter().map(foo).take_while(|e| e.is_some()).collect()

Iterators in Rust are lazily evaluated. In essence, the call to `collect` forces each element of the iterator to be evaluated one at a time. This means that as soon as some element fails the predicate in `take_while`, no further elements will be read from the initial iterator, let alone passed through `map`.

Problem

In Rust, is there are map-like equivalent that stops iterating based on a condition I can choose? I want to iterate over a vector, calling a function on each element as I do so and storing the results, but stop iterating if the function return value ever satisfies a condition Iterative pseudo-code example: ``` results = [] for elem in vec: result = foo(elem) if result is None break results.push(result) ``` I can achieve a clumsy equivalent of this with scan by mutating the initial state but (AFAIK) it will still iterate over every element: Rust-like pseudo-code for scan variant: ``` results = vec.iter().scan(false, |fail, elem| if *fail return None result = foo(elem) if result is None *fail = true return result ).collect() ```

Original source