mirror of
https://github.com/roc-lang/roc.git
synced 2024-11-10 18:08:55 +03:00
Add List.splitFirst and List.splitLast
This commit is contained in:
parent
87f03d1f9f
commit
c87f2fdee1
@ -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.
|
||||
|
Loading…
Reference in New Issue
Block a user