Add List.splitFirst and List.splitLast

This commit is contained in:
Richard Feldman 2022-07-22 09:32:06 -04:00 committed by Folkert
parent 87f03d1f9f
commit c87f2fdee1
No known key found for this signature in database
GPG Key ID: 1F17F6FFD112B97C

View File

@ -51,6 +51,8 @@ interface List
sublist,
intersperse,
split,
splitFirst,
splitLast,
all,
dropIf,
sortAsc,
@ -915,6 +917,41 @@ split = \elements, userSplitIndex ->
{ before, others }
## Returns the list before the first occurrence of a delimiter, as well as the
## rest of the list after that occurrence. If the delimiter is not found, returns `Err`.
##
## List.splitFirst [Foo, Z, Bar, Z, Baz] Z == Ok { before: [Foo], after: [Bar, Baz] }
splitFirst : List elem, elem -> Result { before : List elem, after : List elem } [NotFound]*
splitFirst = \elements, delimiter ->
length = List.len elements
when List.findFirstIndex elements (\elem -> elem == delimiter) is
Ok index ->
before = List.sublist elements { start: 0, len: index }
len = List.len elements - index
Ok { before, len }
Err NotFound -> Err NotFound
## Returns the list before the last occurrence of a delimiter, as well as the
## rest of the list after that occurrence. If the delimiter is not found, returns `Err`.
##
## List.splitLast [Foo, Z, Bar, Z, Baz] Z == Ok { before: [Foo, Bar], after: [Baz] }
splitLast : List elem, elem -> Result { before : List elem, after : List elem } [NotFound]*
splitLast = \elements, delimiter ->
length = List.len elements
when List.findLastIndex elements (\elem -> elem == delimiter) is
Ok index ->
before = List.sublist elements { start: 0, len: index }
len = List.len elements - index
Ok { before, len }
Err NotFound -> Err NotFound
## Like [List.map], except the transformation function returns a [Result].
## If that function ever returns `Err`, [mapTry] immediately returns that `Err`.
## If it returns `Ok` for every element, [mapTry] returns `Ok` with the transformed list.