Skip to content

Instantly share code, notes, and snippets.

@bhgomes
Created April 24, 2021 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhgomes/7d545dde86f6c90e4f25d8fc3d5b9d2d to your computer and use it in GitHub Desktop.
Save bhgomes/7d545dde86f6c90e4f25d8fc3d5b9d2d to your computer and use it in GitHub Desktop.
Rust Iteration Utilities
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