Hey all, I have a classic example of wanting to use fold
-- say I have a method like
A::foo(&self, x: T) -> A
and I have an A
, and a Vec<T>
. I want to essentially call a.foo(t1).foo(t2).foo(t3)
with those t*
variables coming from the Vec<T>
-- a very easy thing to do with a simple ts.iter().fold(a, |a, t| a.foo(t))
.
However, that's not all. Let's say foo
actually returns Result<A, Error>
instead of just A
. So I actually want my closure to be able to return a Result
, and now I want some version of fold
which handles these Result
types and early-out at the first instance of an Err
being returned. That is, fn fold_with_results<B, F, E>(self, init: B, f: F) -> Result<B, E> where F: FnMut(B, Self::Item) -> Result<B, E>
I've run into this a surprising number of times already, and I can't find an easy solution, so I end up using more verbose for
loops.
So is there some trick in std that lets me do something like this? If not, does anyone know of a crate that has such a utility function? (I have found fallible_iterator
but its version of fold
doesn't seem to handle this either).