elm/libraries/Maybe.elm

53 lines
1.1 KiB
Elm
Raw Normal View History

module Maybe where
{-| Represents an optional value. Maybe it is there, maybe it is not.
2013-09-08 22:08:02 +00:00
# Type and Constructors
2013-09-09 22:59:05 +00:00
@docs Maybe
2013-09-08 22:08:02 +00:00
# Taking Maybes apart
@docs maybe, isJust, isNothing
# Maybes and Lists
@docs cons, justs
-}
import Basics (not, (.))
import List (foldr)
2013-09-08 22:08:02 +00:00
{-| The Maybe datatype. Useful when a computation may or may not
result in a value (e.g. logarithm is defined only for positive
numbers).
-}
data Maybe a = Just a | Nothing
2013-09-08 22:08:02 +00:00
{-| Apply a function to the contents of a `Maybe`.
Return default when given `Nothing`.
-}
maybe : b -> (a -> b) -> Maybe a -> b
maybe b f m = case m of
Just v -> f v
Nothing -> b
2013-09-08 22:08:02 +00:00
{-| Check if constructed with `Just`.
-}
isJust : Maybe a -> Bool
isJust = maybe False (\_ -> True)
2013-09-08 22:08:02 +00:00
{-| Check if constructed with `Nothing`.
-}
isNothing : Maybe a -> Bool
isNothing = not . isJust
2013-09-08 22:08:02 +00:00
{-| If `Just`, adds the value to the front of the list.
If `Nothing`, list is unchanged.
-}
cons : Maybe a -> [a] -> [a]
cons mx xs = maybe xs (\x -> x :: xs) mx
2013-09-08 22:08:02 +00:00
{-| Filters out Nothings and extracts the remaining values.
-}
justs : [Maybe a] -> [a]
2013-07-25 22:07:07 +00:00
justs = foldr cons []