merge main

This commit is contained in:
Isaac Van Doren 2024-11-12 20:55:45 -06:00
commit f33a483502
No known key found for this signature in database
GPG key ID: CFA524CD470E5B94
61 changed files with 1775 additions and 1513 deletions

View file

@ -73,6 +73,8 @@ module [
countIf,
chunksOf,
concatUtf8,
forEach!,
forEachTry!,
]
import Bool exposing [Bool, Eq]
@ -1432,3 +1434,45 @@ iterBackwardsHelp = \list, state, f, prevIndex ->
concatUtf8 : List U8, Str -> List U8
expect (List.concatUtf8 [1, 2, 3, 4] "🐦") == [1, 2, 3, 4, 240, 159, 144, 166]
## Run an effectful function for each element on the list.
##
## ```roc
## List.forEach! ["Alice", "Bob", "Charlie"] \name ->
## createAccount! name
## log! "Account created"
## ```
##
## If the function might fail or you need to return early, use [forEachTry!].
forEach! : List a, (a => {}) => {}
forEach! = \list, func! ->
when list is
[] ->
{}
[elem, .. as rest] ->
func! elem
forEach! rest func!
## Run an effectful function that might fail for each element on the list.
##
## If the function returns `Err`, the iteration stops and the error is returned.
##
## ```roc
## List.forEachTry! filesToDelete \path ->
## try File.delete! path
## Stdout.line! "$(path) deleted"
## ```
forEachTry! : List a, (a => Result {} err) => Result {} err
forEachTry! = \list, func! ->
when list is
[] ->
Ok {}
[elem, .. as rest] ->
when func! elem is
Ok {} ->
forEachTry! rest func!
Err err ->
Err err

View file

@ -8,6 +8,7 @@ module [
map2,
try,
onErr,
onErr!,
withDefault,
]
@ -119,3 +120,16 @@ onErr = \result, transform ->
when result is
Ok v -> Ok v
Err e -> transform e
## Like [onErr], but it allows the transformation function to produce effects.
##
## ```roc
## Result.onErr (Err "missing user") \msg ->
## try Stdout.line! "ERROR: $(msg)"
## Err msg
## ```
onErr! : Result a err, (err => Result a otherErr) => Result a otherErr
onErr! = \result, transform! ->
when result is
Ok v -> Ok v
Err e -> transform! e