diff options
author | Sebastian <s@porto5.com> | 2021-01-12 09:09:29 +1100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-01-13 17:01:09 +0000 |
commit | 955226b8ba73a51c7f4803f6ad54a75daf75ae24 (patch) | |
tree | ffd9e3b6fbb3280de63596053b6861655876d97a /src | |
parent | b8000c4ef6100d05ff7912aa0bb59ccb0ce1063a (diff) | |
download | gleam_stdlib-955226b8ba73a51c7f4803f6ad54a75daf75ae24.tar.gz gleam_stdlib-955226b8ba73a51c7f4803f6ad54a75daf75ae24.zip |
Add list.index_fold
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/list.gleam | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 44d1510..4109df5 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -454,6 +454,46 @@ pub fn fold_right(list: List(a), from initial: b, with fun: fn(a, b) -> b) -> b } } +/// Like fold but the folding function also receives the index of the current element. +/// +/// ## Examples +/// +/// ``` +/// ["a", "b", "c"] +/// |> list.index_fold([], fn(index, item, acc) { ... }) +/// ``` +/// +pub fn index_fold( + over over: List(a), + from initial: b, + with fun: fn(Int, a, b) -> b, +) -> b { + over + |> index_map(fn(ix, value) { tuple(ix, value) }) + |> fold( + from: initial, + with: fn(t, acc) { + let tuple(ix, val) = t + fun(ix, val, acc) + }, + ) +} + +pub fn try_fold( + over collection: List(a), + from accumulator: b, + with fun: fn(a, b) -> Result(b, b), +) -> b { + case collection { + [] -> accumulator + [first, ..rest] -> + case fun(first, accumulator) { + Ok(next_accumulator) -> try_fold(rest, next_accumulator, fun) + Error(b) -> b + } + } +} + /// Find the first element in a given list for which the given function returns /// True. /// |