Skip to content

Commit

Permalink
Merge pull request #42 from KurtRMueller/master
Browse files Browse the repository at this point in the history
Create splitWhen function that attempts to split a list at the element where the given predicate is true
  • Loading branch information
mgold authored Apr 25, 2017
2 parents e54e4c4 + 379afe9 commit 6c1a272
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/List/Extra.elm
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ module List.Extra
, scanr1
, unfoldr
, splitAt
, splitWhen
, takeWhileRight
, dropWhileRight
, span
Expand Down Expand Up @@ -879,6 +880,17 @@ splitAt n xs =
( take n xs, drop n xs )


{-| Attempts to split the list at the first element where the given predicate is true. If the predicate is not true for any elements in the list, return nothing. Otherwise, return the split list.
splitWhen (\n -> n == 3) [1,2,3,4,5] == Just ([1,2],[3,4,5])
splitWhen (\n -> n == 6) [1,2,3,4,5] == Nothing
-}
splitWhen : (a -> Bool) -> List a -> Maybe ( List a, List a )
splitWhen predicate list =
findIndex predicate list
|> Maybe.map (\i -> splitAt i list)


{-| Take elements from the right, while predicate still holds.
takeWhileRight ((<)5) (range 1 10) == [6,7,8,9,10]
Expand Down
8 changes: 8 additions & 0 deletions tests/Tests.elm
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,14 @@ all =
\() ->
Expect.equal (splitAt (-1) [ 1, 2, 3 ]) ( [], [ 1, 2, 3 ] )
]
, describe "splitWhen" <|
[ test "returns split list when predicate is true" <|
\() ->
Expect.equal (splitWhen (\n -> n == 3) [ 1, 2, 3, 4, 5]) (Just ([1, 2], [3, 4, 5]))
, test "returns nothing when predicate is false" <|
\() ->
Expect.equal (splitWhen (\n -> n == 6) [ 1, 2, 3, 4, 5]) Nothing
]
, describe "takeWhileRight" <|
[ test "" <|
\() ->
Expand Down

0 comments on commit 6c1a272

Please sign in to comment.