Skip to content

Commit ec65c09

Browse files
sportolpil
authored andcommitted
Update try_fold to return Result(a,e)
1 parent 66b107b commit ec65c09

File tree

2 files changed

+24
-12
lines changed

2 files changed

+24
-12
lines changed

src/gleam/list.gleam

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -479,11 +479,11 @@ pub fn index_fold(
479479
)
480480
}
481481

482-
/// A variant of fold that allows to stop folding earlier.
482+
/// A variant of fold that might fail.
483483
///
484-
/// The folding function should return `Result(accumulator, accumulator)
484+
/// The folding function should return `Result(accumulator, error)
485485
/// If the returned value is `Ok(accumulator)` try_fold will try the next value in the list.
486-
/// If the returned value is `Error(accumulator)` try_fold will stop and return that accumulator.
486+
/// If the returned value is `Error(error)` try_fold will stop and return that error.
487487
///
488488
/// ## Examples
489489
///
@@ -492,22 +492,22 @@ pub fn index_fold(
492492
/// |> try_fold(0, fn(i, acc) {
493493
/// case i < 3 {
494494
/// True -> Ok(acc + i)
495-
/// False -> Error(acc)
495+
/// False -> Error(Nil)
496496
/// }
497497
/// })
498498
/// ```
499499
///
500500
pub fn try_fold(
501501
over collection: List(a),
502502
from accumulator: b,
503-
with fun: fn(a, b) -> Result(b, b),
504-
) -> b {
503+
with fun: fn(a, b) -> Result(b, e),
504+
) -> Result(b, e) {
505505
case collection {
506-
[] -> accumulator
506+
[] -> Ok(accumulator)
507507
[first, ..rest] ->
508508
case fun(first, accumulator) {
509509
Ok(next_accumulator) -> try_fold(rest, next_accumulator, fun)
510-
Error(b) -> b
510+
Error(err) -> Error(err)
511511
}
512512
}
513513
}

test/gleam/list_test.gleam

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -180,15 +180,27 @@ pub fn index_fold_test() {
180180
pub fn try_fold_test() {
181181
[1, 2, 3]
182182
|> list.try_fold(
183-
[],
183+
0,
184+
fn(i, acc) {
185+
case i < 4 {
186+
True -> Ok(acc + i)
187+
False -> Error(Nil)
188+
}
189+
},
190+
)
191+
|> should.equal(Ok(6))
192+
193+
[1, 2, 3]
194+
|> list.try_fold(
195+
0,
184196
fn(i, acc) {
185197
case i < 3 {
186-
True -> Ok([i, ..acc])
187-
False -> Error(acc)
198+
True -> Ok(acc + i)
199+
False -> Error(Nil)
188200
}
189201
},
190202
)
191-
|> should.equal([2, 1])
203+
|> should.equal(Error(Nil))
192204
}
193205

194206
pub fn find_map_test() {

0 commit comments

Comments
 (0)