Add List.appendIfOk and List.prependIfOk

This commit is contained in:
Richard Feldman 2023-07-15 22:22:50 -04:00 committed by Folkert
parent f0e3d65bc9
commit e59d4e57c5
No known key found for this signature in database
GPG key ID: 1F17F6FFD112B97C
3 changed files with 41 additions and 2 deletions

View file

@ -6,6 +6,9 @@ interface List
replace,
update,
append,
appendIfOk,
prepend,
prependIfOk,
map,
len,
withCapacity,
@ -15,7 +18,6 @@ interface List
single,
repeat,
reverse,
prepend,
join,
keepIf,
contains,
@ -320,6 +322,21 @@ append = \list, element ->
|> List.reserve 1
|> List.appendUnsafe element
## If the given [Result] is `Ok`, add it to the end of a list.
## Otherwise, return the list unmodified.
##
## ```
## List.appendIfOk [1, 2, 3] (Ok 4)
##
## [0, 1, 2]
## |> List.appendIfOk (Err 3)
## ```
appendIfOk : List a, Result a * -> List a
appendIfOk = \list, result ->
when result is
Ok elem -> append list elem
Err _ -> list
## Writes the element after the current last element unconditionally.
## In other words, it is assumed that
##
@ -336,6 +353,21 @@ appendUnsafe : List a, a -> List a
## ```
prepend : List a, a -> List a
## If the given [Result] is `Ok`, add it to the beginning of a list.
## Otherwise, return the list unmodified.
##
## ```
## List.prepend [1, 2, 3] (Ok 0)
##
## [2, 3, 4]
## |> List.prepend (Err 1)
## ```
prependIfOk : List a, Result a * -> List a
prependIfOk = \list, result ->
when result is
Ok elem -> prepend list elem
Err _ -> list
## Returns the length of the list - the number of elements it contains.
##
## One [List] can store up to 2,147,483,648 elements (just over 2 billion), which