aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorRobert Attard <robert.attard@mail.mcgill.ca>2021-04-13 10:04:17 -0400
committerLouis Pilfold <louis@lpil.uk>2021-04-14 21:23:32 +0100
commit53471ea469a5ce92a500194405a121237de5d131 (patch)
tree7af335b2afebb9098e58560367c5362de6adf86b /src
parentfb129be0608b54412f5a70faefff5903acd5d014 (diff)
downloadgleam_stdlib-53471ea469a5ce92a500194405a121237de5d131.tar.gz
gleam_stdlib-53471ea469a5ce92a500194405a121237de5d131.zip
add list.scan
Diffstat (limited to 'src')
-rw-r--r--src/gleam/list.gleam30
1 files changed, 30 insertions, 0 deletions
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)
+}