Created
April 24, 2021 20:32
-
-
Save bhgomes/7d545dde86f6c90e4f25d8fc3d5b9d2d to your computer and use it in GitHub Desktop.
Rust Iteration Utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use core::fmt; | |
/// Folds an iterator with a spacer. | |
pub fn fold_iter_with_spacer<I, F, S, T, E>( | |
iter: I, | |
init: T, | |
mut f: F, | |
mut spacer: S, | |
) -> Option<Result<T, E>> | |
where | |
I: IntoIterator, | |
F: FnMut(I::Item) -> Result<T, E>, | |
S: FnMut() -> Result<T, E>, | |
{ | |
let mut iter = iter.into_iter(); | |
iter.next() | |
.map(move |n| f(n).and(iter.try_fold(init, move |_, t| spacer().and(f(t))))) | |
} | |
/// Formats an iterator pointwise with a spacer. | |
pub fn format_iter_with_spacer<I, FT, FS>( | |
iter: I, | |
f: &mut fmt::Formatter, | |
format: FT, | |
format_spacer: FS, | |
) -> fmt::Result | |
where | |
I: IntoIterator, | |
FT: Fn(I::Item, &mut fmt::Formatter) -> fmt::Result, | |
FS: Fn(&mut fmt::Formatter) -> fmt::Result, | |
{ | |
let mut iter = iter.into_iter(); | |
iter.next() | |
.map(move |n| { | |
format(n, f).and(iter.try_fold((), move |_, t| format_spacer(f).and(format(t, f)))) | |
}) | |
.unwrap_or(Ok(())) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment