File tree Expand file tree Collapse file tree 2 files changed +24
-12
lines changed Expand file tree Collapse file tree 2 files changed +24
-12
lines changed Original file line number Diff line number Diff line change @@ -479,11 +479,11 @@ pub fn index_fold(
479
479
)
480
480
}
481
481
482
- /// A variant of fold that allows to stop folding earlier .
482
+ /// A variant of fold that might fail .
483
483
///
484
- /// The folding function should return `Result(accumulator, accumulator )
484
+ /// The folding function should return `Result(accumulator, error )
485
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 .
486
+ /// If the returned value is `Error(error )` try_fold will stop and return that error .
487
487
///
488
488
/// ## Examples
489
489
///
@@ -492,22 +492,22 @@ pub fn index_fold(
492
492
/// |> try_fold(0, fn(i, acc) {
493
493
/// case i < 3 {
494
494
/// True -> Ok(acc + i)
495
- /// False -> Error(acc )
495
+ /// False -> Error(Nil )
496
496
/// }
497
497
/// })
498
498
/// ```
499
499
///
500
500
pub fn try_fold(
501
501
over collection: List(a),
502
502
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) {
505
505
case collection {
506
- [] -> accumulator
506
+ [] -> Ok( accumulator)
507
507
[first, ..rest] ->
508
508
case fun(first, accumulator) {
509
509
Ok(next_accumulator) -> try_fold(rest, next_accumulator, fun)
510
- Error(b ) -> b
510
+ Error(err ) -> Error(err)
511
511
}
512
512
}
513
513
}
Original file line number Diff line number Diff line change @@ -180,15 +180,27 @@ pub fn index_fold_test() {
180
180
pub fn try_fold_test ( ) {
181
181
[ 1 , 2 , 3 ]
182
182
|> 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 ,
184
196
fn ( i , acc ) {
185
197
case i < 3 {
186
- True -> Ok ( [ i , .. acc ] )
187
- False -> Error ( acc )
198
+ True -> Ok ( acc + i )
199
+ False -> Error ( Nil )
188
200
}
189
201
} ,
190
202
)
191
- |> should . equal ( [ 2 , 1 ] )
203
+ |> should . equal ( Error ( Nil ) )
192
204
}
193
205
194
206
pub fn find_map_test ( ) {
You can’t perform that action at this time.
0 commit comments