I'm pretty new to Rust and to it's async/await model, and I'm trying to do something that looks like a specialized Haskell's traverse
function. Given a Vec<T>
and a function T -> Future<Output = R>
I want to get a Future<Output = Vec<R>>
.
At the moment, I have the following:
use futures::{FutureExt, StreamExt};
pub async fn traverse<I, T, R, F, FN>(xs: I, f: FN) -> Vec<R>
where
I: IntoIterator<Item = T>,
F: FutureExt<Output = R>,
FN: Fn(T) -> F,
{
futures::stream::iter(xs)
.fold(vec![], |acc, item| {
f(item).map(move |app| {
let mut a = acc;
a.push(app);
a
})
})
.await
}
It works as expected, but doesn't feel very idiomatic. Does anybody has suggestion how to improve this function?
traverse
function is a generalized way to transform a Vec of Future to a Future of Vec. you can get back the expected behaviour by passing the vector of Future as first argument and the second argument must be the identity function|x| x
\$\endgroup\$