diff --git a/src/List/Extra.elm b/src/List/Extra.elm index 2210621..2067801 100644 --- a/src/List/Extra.elm +++ b/src/List/Extra.elm @@ -40,6 +40,7 @@ module List.Extra , scanr1 , unfoldr , splitAt + , splitWhen , takeWhileRight , dropWhileRight , span @@ -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] diff --git a/tests/Tests.elm b/tests/Tests.elm index 521fa78..46848f3 100644 --- a/tests/Tests.elm +++ b/tests/Tests.elm @@ -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 "" <| \() ->