I'm looking for a recursive version of Option::and_then
.
By that I mean that for an Option
value, and_then(f)
is called again and again recursively as long as the return value of f
is Some(...)
, until stopping on None
.
For a toy example:
let mut v = Vec::new();
Some(5).and_then_recurse(|n| match n {
0 => None,
_ => {
v.push(n);
Some(n - 1)
}
});
assert_eq!(vec![5, 4, 3, 2, 1], v);
My implementation of this:
impl<T, F> AndThenRecurse<T, F> for Option<T>
where
F: FnMut(T) -> Option<T>,
{
fn and_then_recurse(self, mut f: F) -> Option<T> {
match self {
None => None,
Some(t) => f(t).and_then_recurse(f)
}
}
}
My question would be:
Is there already something like this in the standard library, or some combination of functions that does this without requiring explicit recursion on my part?