Skip to content

add splitOn #182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/List/Extra.elm
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module List.Extra exposing
, lift2, lift3, lift4
, groupsOf, groupsOfWithStep, groupsOfVarying, greedyGroupsOf, greedyGroupsOfWithStep
, joinOn
, splitOn
)

{-| Convenience functions for working with List
Expand Down Expand Up @@ -1564,6 +1565,52 @@ splitWhen predicate list =
|> Maybe.map (\i -> splitAt i list)


{-| Split a list into sublists, starting a new sublist with each element that satisfies a predicate.

splitOn ((==) 3) [ 1, 2, 3, 4, 5 ]
--> [ [ 1, 2 ], [ 3, 4, 5 ] ]

splitOn ((==) 3) [ 3, 1, 2, 3, 3, 4, 5, 3 ]
--> [ [ 3, 1, 2 ], [ 3 ], [ 3, 4, 5 ], [ 3 ] ]

Single-pass algorithm without using reverse or list concatenation.
Inspiration: <https://www.brics.dk/RS/01/39/BRICS-RS-01-39.pdf>

-}
splitOn : (a -> Bool) -> List a -> List (List a)
splitOn pred xs =
let
fields list =
case list of
[] ->
[]

x :: rest ->
let
( w, r ) =
word rest
in
(x :: w) :: fields r

word list =
case list of
[] ->
( [], [] )

x :: rest ->
if pred x then
( [], list )

else
let
( w, r ) =
word rest
in
( x :: w, r )
in
fields xs


{-| Take elements from the right, while predicate still holds.

takeWhileRight ((<) 5) (List.range 1 10)
Expand Down
8 changes: 8 additions & 0 deletions tests/Tests.elm
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,14 @@ all =
\() ->
Expect.equal (splitWhen (\n -> n == 6) [ 1, 2, 3, 4, 5 ]) Nothing
]
, describe "splitOn" <|
[ test "splits a list beginning with each element for which the predicate is true" <|
\() ->
Expect.equal (splitOn ((==) 3) [ 1, 2, 3, 3, 4, 5 ]) [ [ 1, 2 ], [ 3, 4, 5 ] ]
, test "doesn't falter on edge cases" <|
\() ->
Expect.equal (splitOn ((==) 3) [ 3, 1, 2, 3, 3, 4, 5, 3 ]) [ [ 3, 1, 2 ], [ 3 ], [ 3, 4, 5 ], [ 3 ] ]
]
, describe "takeWhileRight" <|
[ test "keeps the correct items" <|
\() ->
Expand Down