Skip to content

Commit 107ce9b

Browse files
sportolpil
authored andcommitted
Refactor index_fold to do only one pass
1 parent ec65c09 commit 107ce9b

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

src/gleam/list.gleam

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,14 @@ pub fn fold_right(list: List(a), from initial: b, with fun: fn(a, b) -> b) -> b
454454
}
455455
}
456456

457+
fn index_fold_(over: List(a), acc: b, with: fn(Int, a, b) -> b, index: Int) -> b {
458+
case over {
459+
[] -> acc
460+
[first, ..rest] ->
461+
index_fold_(rest, with(index, first, acc), with, index + 1)
462+
}
463+
}
464+
457465
/// Like fold but the folding function also receives the index of the current element.
458466
///
459467
/// ## Examples
@@ -468,15 +476,7 @@ pub fn index_fold(
468476
from initial: b,
469477
with fun: fn(Int, a, b) -> b,
470478
) -> b {
471-
over
472-
|> index_map(fn(ix, value) { tuple(ix, value) })
473-
|> fold(
474-
from: initial,
475-
with: fn(t, acc) {
476-
let tuple(ix, val) = t
477-
fun(ix, val, acc)
478-
},
479-
)
479+
index_fold_(over, initial, fun, 0)
480480
}
481481

482482
/// A variant of fold that might fail.

0 commit comments

Comments
 (0)