Skip to content

Feature request: a running fold adaptor #798

Open
@ronnodas

Description

@ronnodas

It's often useful to keep track of the intermediate results in a fold, as in Haskell's scanl, for example if you want to turn a iterator of numbers into an iterator of running totals. At first this looks like a job for scan, but it was easier to write using successors, as follows:

pub fn fold_map<I, B, F>(iter: I, init: B, mut f: F) -> impl Iterator<Item = B>
where
    I: IntoIterator,
    F: FnMut(&B, I::Item) -> B,
{
    let mut iter = iter.into_iter();
    std::iter::successors(Some(init), move |prev| iter.next().map(|x| f(prev, x)))
}

Then fold_map(1..4, 0, |x, y| x + y).collect_vec() produces [0, 1, 3, 6], see playground link.

Could a version of this be added to itertools?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions