How do I replicate Haskell's `scanl (+) 0 xs` in Rust?

Edit :

Despite the old version of this answer mimics the behavior of scanl's intermediate form, the execution wasn't lazy. Updated the generic implementation from my old answer with @French Boiethios's answer.

This is the implementation :

fn scanl<'u, T, F>(op: F, initial: T, list: &'u [T]) -> impl Iterator<Item = T> + 'u
where
    F: Fn(&T, &T) -> T + 'u,
{
    let mut iter = list.iter();
    std::iter::successors(Some(initial), move |acc| iter.next().map(|n| op(n, acc)))
}
//scanl(|x, y| x + y, 0, &[1, 2, 3, 4, 5]).collect::<Vec<_>>()

Playground


It can be easily implemented by a fold

For an Add operation:

let result = xs.iter().fold(vec![0], |mut acc, val| {
    acc.push(val + acc.last().unwrap());
    acc
});

Playground


Here is the generic version :

fn scanl<T, F>(op: F, initial: T, list: &[T]) -> Vec<T>
where
    F: Fn(&T, &T) -> T,
{
    let mut acc = Vec::with_capacity(list.len());
    acc.push(initial);

    list.iter().fold(acc, |mut acc, val| {
        acc.push(op(val, acc.last().unwrap()));
        acc
    })
}
//scanl(|x, y| x + y, 0, &[1, 2, 3, 4, 5])

Playground


I would do that with successors:

fn main() {
    let mut xs = vec![1, 2, 3, 4, 5].into_iter();
    let vs = std::iter::successors(Some(0), |acc| xs.next().map(|n| n + *acc));

    assert_eq!(vs.collect::<Vec<_>>(), [0, 1, 3, 6, 10, 15]);
}

The awkward scan behaviour of having to mutate the accumulator can be explained by a lack of GC.

There is nothing preventing Rust from doing what you ask.

Example of possible implementation:

pub struct Mapscan<I, A, F> {
    accu: Option<A>,
    iter: I,
    f: F,
}

impl<I, A, F> Mapscan<I, A, F> {
    pub fn new(iter: I, accu: Option<A>, f: F) -> Self {
        Self { iter, accu, f }
    }
}

impl<I, A, F> Iterator for Mapscan<I, A, F>
where
    I: Iterator,
    F: FnMut(&A, I::Item) -> Option<A>,
{
    type Item = A;

    fn next(&mut self) -> Option<Self::Item> {
        self.accu.take().map(|accu| {
            self.accu = self.iter.next().and_then(|item| (self.f)(&accu, item));
            accu
        })
    }
}

trait IterPlus: Iterator {
    fn map_scan<A, F>(self, accu: Option<A>, f: F) -> Mapscan<Self, A, F>
    where
        Self: Sized,
        F: FnMut(&A, Self::Item) -> Option<A>,
    {
        Mapscan::new(self, accu, f)
    }
}

impl<T: ?Sized> IterPlus for T where T: Iterator {}

fn main() {
    let xs = [1, 2, 3, 4, 5];

    let vs = xs
        .iter()
        .map_scan(Some(0), |acc, x| Some(acc + x));

    assert_eq!(vs.collect::<Vec<_>>(), [0, 1, 3, 6, 10, 15]);
}

Tags:

Haskell

Rust