elm-community/maybe-extra/1.0.0

NOTE: this package is not compatible with Elm 0.19.1

Maybe.Extra

Convenience functions for Maybe.

Common helpers

(?) : Maybe a -> a -> a

Flipped, infix version of withDefault.

head [] ? 0 == 0
join : Maybe (Maybe a) -> Maybe a

Flattens nested Maybes

join (Just (Just 1)) == Just 1
join (Just Nothing)  == Nothing
join Nothing         == Nothing
isNothing : Maybe a -> Bool

Conveniently check if a Maybe matches Nothing.

isNothing (Just 42) == False
isNothing (Just []) == False
isNothing Nothing   == True
isJust : Maybe a -> Bool

Conveniently check if a Maybe matches Just _.

isJust (Just 42) == True
isJust (Just []) == True
isJust Nothing   == False
mapDefault : b -> (a -> b) -> Maybe a -> b

Take a default value, a function and a Maybe. Return the default value if the Maybe is Nothing. If the Maybe is Just a, apply the function on a and return the b. That is, mapDefault d f is equivalent to Maybe.map f >> Maybe.withDefault d.

Applicative functions

andMap : Maybe (a -> b) -> Maybe a -> Maybe b

Apply the function that is inside Maybe to a value that is inside Maybe. Return the result inside Maybe. If one of the Maybe arguments is Nothing, return Nothing.

Just ((+)2) `andMap` Just 3 == Just 5
Just Nothing `andMap` Just 3 == Nothing
Just ((+)2) `andMap` Nothing == Nothing

Advanced functional programmers will recognize this as the implementation of <*> for Maybes from the Applicative typeclass.

or : Maybe a -> Maybe a -> Maybe a

Like the boolean '||' this will return the first value that is positive ('Just').

Just 4 `or` Just 5    == Just 4
Just 4 `or` Nothing   == Just 4
Nothing `or` Just 5   == Just 5
Nothing `or` Nothing  == Nothing

This function sort of works like 'oneOf' but on single 'Maybe's.

Advanced functional programmers will recognize this as the implementation of 'mplus' for Maybes from the 'MonadPlus' Typeclass.

List and array functions

maybeToList : Maybe a -> List a

Return an empty list on Nothing or a list with one element, where the element is the value of Just.

maybeToList Nothing == []
maybeToList (Just 1) == [1]
maybeToArray : Maybe a -> Array a

Return an empty array on Nothing or a list with one element, where the element is the value of Just.

maybeToArray Nothing == Array.fromList []
maybeToArray (Just 1) == Array.fromList [1]
traverse : (a -> Maybe b) -> List a -> Maybe (List b)

Take a function that returns Maybe value and a list. Map a function over each element of the list. Collect the result in the list within Maybe.

traverse (\x -> Just (x*10)) [1,2,3,4,5] == Just [10,20,30,40,50]
combine : List (Maybe a) -> Maybe (List a)

Take a list of Maybes and return a Maybe with a list of values. combine == traverse identity.

combine [] == Just []
combine [Just 1, Just 2, Just 3] == Just [1,2,3]
combine [Just 1, Nothing, Just 3] == Nothing
traverseArray : (a -> Maybe b) -> Array a -> Maybe (Array b)
combineArray : Array (Maybe a) -> Maybe (Array a)