From 66b107b1902936411c8532113dcdd3d535176c05 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Tue, 12 Jan 2021 09:21:30 +1100 Subject: Add try_fold --- src/gleam/list.gleam | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') 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, -- cgit v1.2.3