aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSebastian <s@porto5.com>2021-01-13 10:59:26 +1100
committerLouis Pilfold <louis@lpil.uk>2021-01-13 17:01:09 +0000
commitec65c09aacb30c2b6ad96bcf407d2243cc27bb91 (patch)
tree4e41582d588bc6c43a857c61e1b8808b50579513
parent66b107b1902936411c8532113dcdd3d535176c05 (diff)
downloadgleam_stdlib-ec65c09aacb30c2b6ad96bcf407d2243cc27bb91.tar.gz
gleam_stdlib-ec65c09aacb30c2b6ad96bcf407d2243cc27bb91.zip
Update try_fold to return `Result(a,e)`
-rw-r--r--src/gleam/list.gleam16
-rw-r--r--test/gleam/list_test.gleam20
2 files changed, 24 insertions, 12 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index b156b3f..c93f9eb 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -479,11 +479,11 @@ pub fn index_fold(
)
}
-/// A variant of fold that allows to stop folding earlier.
+/// A variant of fold that might fail.
///
-/// The folding function should return `Result(accumulator, accumulator)
+/// The folding function should return `Result(accumulator, error)
/// If the returned value is `Ok(accumulator)` try_fold will try the next value in the list.
-/// If the returned value is `Error(accumulator)` try_fold will stop and return that accumulator.
+/// If the returned value is `Error(error)` try_fold will stop and return that error.
///
/// ## Examples
///
@@ -492,7 +492,7 @@ pub fn index_fold(
/// |> try_fold(0, fn(i, acc) {
/// case i < 3 {
/// True -> Ok(acc + i)
-/// False -> Error(acc)
+/// False -> Error(Nil)
/// }
/// })
/// ```
@@ -500,14 +500,14 @@ pub fn index_fold(
pub fn try_fold(
over collection: List(a),
from accumulator: b,
- with fun: fn(a, b) -> Result(b, b),
-) -> b {
+ with fun: fn(a, b) -> Result(b, e),
+) -> Result(b, e) {
case collection {
- [] -> accumulator
+ [] -> Ok(accumulator)
[first, ..rest] ->
case fun(first, accumulator) {
Ok(next_accumulator) -> try_fold(rest, next_accumulator, fun)
- Error(b) -> b
+ Error(err) -> Error(err)
}
}
}
diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam
index dfc9693..3bd463a 100644
--- a/test/gleam/list_test.gleam
+++ b/test/gleam/list_test.gleam
@@ -180,15 +180,27 @@ pub fn index_fold_test() {
pub fn try_fold_test() {
[1, 2, 3]
|> list.try_fold(
- [],
+ 0,
+ fn(i, acc) {
+ case i < 4 {
+ True -> Ok(acc + i)
+ False -> Error(Nil)
+ }
+ },
+ )
+ |> should.equal(Ok(6))
+
+ [1, 2, 3]
+ |> list.try_fold(
+ 0,
fn(i, acc) {
case i < 3 {
- True -> Ok([i, ..acc])
- False -> Error(acc)
+ True -> Ok(acc + i)
+ False -> Error(Nil)
}
},
)
- |> should.equal([2, 1])
+ |> should.equal(Error(Nil))
}
pub fn find_map_test() {