From 53471ea469a5ce92a500194405a121237de5d131 Mon Sep 17 00:00:00 2001 From: Robert Attard Date: Tue, 13 Apr 2021 10:04:17 -0400 Subject: add list.scan --- src/gleam/list.gleam | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'src') diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index dc03ec1..9f88063 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1401,3 +1401,33 @@ pub fn reduce(over list: List(a), with fun: fn(a, a) -> a) -> Result(a, Nil) { |> Ok } } + +fn do_scan( + list: List(a), + accumulator: b, + accumulated: List(b), + fun: fn(a, b) -> b, +) -> List(b) { + case list { + [] -> reverse(accumulated) + [x, ..xs] -> { + let next = fun(x, accumulator) + do_scan(xs, next, [next, ..accumulated], fun) + } + } +} + +/// Similar to `fold`, but yields the state of the accumulator at each stage. +/// +/// ## Examples +/// +/// > scan(over: [1, 2, 3], from: 100, with: fn(i, acc) { acc + i }) +/// [101, 103, 106] +/// +pub fn scan( + over list: List(a), + from initial: b, + with fun: fn(a, b) -> b, +) -> List(b) { + do_scan(list, initial, [], fun) +} -- cgit v1.2.3