Skip to content

Commit 66b107b

Browse files
sportolpil
authored andcommitted
Add try_fold
1 parent 955226b commit 66b107b

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
- The `result` module gains the `lazy_or`, `lazy_unwrap`, and `replace_error` functions.
88
- The `bool` module gains the `nand`, `nor`, `exclusive_nor`, and `exclusive_or` functions.
99
- The `bit_builder` module gains the `from_string_builder` function.
10-
- The `list` modules gains the `index_fold`, and `permutations` functions.
10+
- The `list` modules gains the `index_fold`, `permutations`, and `try_fold` functions.
1111
- Breaking change in `queue.from_list`. The head element in the list becomes the first element in the queue.
1212
- Fix `queue.pop_back` and `queue.pop_front`
1313

src/gleam/list.gleam

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

482+
/// A variant of fold that allows to stop folding earlier.
483+
///
484+
/// The folding function should return `Result(accumulator, accumulator)
485+
/// 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.
487+
///
488+
/// ## Examples
489+
///
490+
/// ```
491+
/// [1, 2, 3, 4]
492+
/// |> try_fold(0, fn(i, acc) {
493+
/// case i < 3 {
494+
/// True -> Ok(acc + i)
495+
/// False -> Error(acc)
496+
/// }
497+
/// })
498+
/// ```
499+
///
482500
pub fn try_fold(
483501
over collection: List(a),
484502
from accumulator: b,

test/gleam/list_test.gleam

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,20 @@ pub fn index_fold_test() {
177177
|> should.equal([tuple(2, "c"), tuple(1, "b"), tuple(0, "a")])
178178
}
179179

180+
pub fn try_fold_test() {
181+
[1, 2, 3]
182+
|> list.try_fold(
183+
[],
184+
fn(i, acc) {
185+
case i < 3 {
186+
True -> Ok([i, ..acc])
187+
False -> Error(acc)
188+
}
189+
},
190+
)
191+
|> should.equal([2, 1])
192+
}
193+
180194
pub fn find_map_test() {
181195
let f = fn(x) {
182196
case x {

0 commit comments

Comments
 (0)