aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/gleam/list.gleam18
1 files changed, 18 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index 4109df5..b156b3f 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -479,6 +479,24 @@ pub fn index_fold(
)
}
+/// A variant of fold that allows to stop folding earlier.
+///
+/// The folding function should return `Result(accumulator, accumulator)
+/// 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.
+///
+/// ## Examples
+///
+/// ```
+/// [1, 2, 3, 4]
+/// |> try_fold(0, fn(i, acc) {
+/// case i < 3 {
+/// True -> Ok(acc + i)
+/// False -> Error(acc)
+/// }
+/// })
+/// ```
+///
pub fn try_fold(
over collection: List(a),
from accumulator: b,