AgreeableLandscape@lemmy.mlM to Rust Programming@lemmy.ml · 3 years ago"Rust needs evert(), which turns an iterator over Result of T into a Result of a collection of T or a collection of errors" Thoughts on this?cybre.spaceexternal-linkmessage-square7fedilinkarrow-up112arrow-down11
arrow-up111arrow-down1external-link"Rust needs evert(), which turns an iterator over Result of T into a Result of a collection of T or a collection of errors" Thoughts on this?cybre.spaceAgreeableLandscape@lemmy.mlM to Rust Programming@lemmy.ml · 3 years agomessage-square7fedilink
minus-squareAode (He/They)@lemmy.mllinkfedilinkarrow-up1·edit-23 years agoi might try let res = collection.into_iter().map(|item| item.fallible_operation()).fold(Ok(Vec::new()), |acc, res| { match (acc, res) { (Ok(mut vec), Ok(item)) => { vec.push(item); Ok(vec) (Err(mut vec), Err(error)) => { vec.push(error); Err(vec) } (Ok(_), Err(error)) => Err(vec![error]), _ => acc, } }); Maybe expand it with pub trait Evert<T, E> { fn evert(self) -> Result<Vec<T>, Vec<E>>; } impl<I, T, E> Evert<T, E> for I where I: IntoIterator<Item = Result<T, E>>, { fn evert(self) -> Result<Vec<T>, Vec<E>> { self.into_iter().fold(/* implementation from above */) } } fn main() { let result = vec![Ok(1), Err(3), Ok(4), Err(8)].evert(); assert_eq!(result, Err(vec![3, 8])); }
minus-squareAode (He/They)@lemmy.mllinkfedilinkarrow-up2·3 years agoplayground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=39a1c5c855a4c3d5d537f446c3b72783
i might try
let res = collection.into_iter().map(|item| item.fallible_operation()).fold(Ok(Vec::new()), |acc, res| { match (acc, res) { (Ok(mut vec), Ok(item)) => { vec.push(item); Ok(vec) (Err(mut vec), Err(error)) => { vec.push(error); Err(vec) } (Ok(_), Err(error)) => Err(vec![error]), _ => acc, } });
Maybe expand it with
pub trait Evert<T, E> { fn evert(self) -> Result<Vec<T>, Vec<E>>; } impl<I, T, E> Evert<T, E> for I where I: IntoIterator<Item = Result<T, E>>, { fn evert(self) -> Result<Vec<T>, Vec<E>> { self.into_iter().fold(/* implementation from above */) } } fn main() { let result = vec![Ok(1), Err(3), Ok(4), Err(8)].evert(); assert_eq!(result, Err(vec![3, 8])); }
playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=39a1c5c855a4c3d5d537f446c3b72783