Recursive `and_then`

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?

You can do something similar with std::iter::successors:

let v: Vec<i32> = std::iter::successors(Some(5), |n| match n {
    1 => None,
    _ => Some(n - 1)
}).collect();
assert_eq!(v, vec![5,4,3,2,1]);
5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.