elm-review/tests/List/Extra.elm

44 lines
967 B
Elm
Raw Normal View History

2022-04-17 09:59:11 +03:00
module List.Extra exposing (find, indexedFilterMap)
2021-08-19 21:57:29 +03:00
{-| Some utilities.
-}
{-| Find the first element that satisfies a predicate and return
Just that element. If none match, return Nothing.
find (\num -> num > 5) [ 2, 4, 6, 8 ] == Just 6
-}
find : (a -> Bool) -> List a -> Maybe a
find predicate list =
case list of
[] ->
Nothing
first :: rest ->
if predicate first then
Just first
else
find predicate rest
2022-04-17 09:59:11 +03:00
indexedFilterMap : (Int -> a -> Maybe b) -> Int -> List a -> List b -> List b
indexedFilterMap predicate index list acc =
case list of
[] ->
acc
x :: xs ->
2022-11-09 16:27:54 +03:00
indexedFilterMap predicate
(index + 1)
xs
(case predicate index x of
Just b ->
b :: acc
Nothing ->
acc
)