diff options
author | Sebastian <s@porto5.com> | 2021-01-13 11:10:47 +1100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-01-13 17:01:09 +0000 |
commit | 107ce9bc60cb971c44a02648bef232336fbbdbf3 (patch) | |
tree | 568581bc4e5c23f1e5fcd4c1ce37036aa22083dd | |
parent | ec65c09aacb30c2b6ad96bcf407d2243cc27bb91 (diff) | |
download | gleam_stdlib-107ce9bc60cb971c44a02648bef232336fbbdbf3.tar.gz gleam_stdlib-107ce9bc60cb971c44a02648bef232336fbbdbf3.zip |
Refactor index_fold to do only one pass
-rw-r--r-- | src/gleam/list.gleam | 18 |
1 files changed, 9 insertions, 9 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index c93f9eb..32d6675 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -454,6 +454,14 @@ pub fn fold_right(list: List(a), from initial: b, with fun: fn(a, b) -> b) -> b } } +fn index_fold_(over: List(a), acc: b, with: fn(Int, a, b) -> b, index: Int) -> b { + case over { + [] -> acc + [first, ..rest] -> + index_fold_(rest, with(index, first, acc), with, index + 1) + } +} + /// Like fold but the folding function also receives the index of the current element. /// /// ## Examples @@ -468,15 +476,7 @@ pub fn index_fold( 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) - }, - ) + index_fold_(over, initial, fun, 0) } /// A variant of fold that might fail. |