Find element to the left/right of given predicate

I know about Iterator in std::iter - Rust

Which takes an iterator + predicate, and returns an Option<Item> of the first elem that satisfies the condition.

I want something slightly different:

the element to the LEFT of the first element that satisfies the condition (if item 0 satisfies, return NONE)

the element to the RIGHT of the first element that satisfies the condition (if last item, return NONE)

Now, I can certainly do this manually with a for loop and some book keeping. However, is there an idiomatic / pure way to do this ?

Right

iter.by_ref().find(pred)
    .and_then(|_| iter.next())

left

iter.try_fold(None, |acc, item| if pred(&item) {
    Err(acc)
} else {
    Ok(Some(item))
})
    .err()
    .flatten()
4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.