2013-02-27 07:26:28 +00:00
|
|
|
module Maybe where
|
|
|
|
|
2013-09-09 23:32:12 +00:00
|
|
|
{-| 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
|
|
|
|
-}
|
|
|
|
|
2013-07-26 10:25:04 +00:00
|
|
|
import Basics (not, (.))
|
|
|
|
import List (foldr)
|
2013-02-27 07:26:28 +00:00
|
|
|
|
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).
|
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
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`.
|
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
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`.
|
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
isJust : Maybe a -> Bool
|
|
|
|
isJust = maybe False (\_ -> True)
|
|
|
|
|
2013-09-08 22:08:02 +00:00
|
|
|
{-| Check if constructed with `Nothing`.
|
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
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.
|
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
cons : Maybe a -> [a] -> [a]
|
2013-03-10 09:07:17 +00:00
|
|
|
cons mx xs = maybe xs (\x -> x :: xs) mx
|
2013-02-27 07:26:28 +00:00
|
|
|
|
2013-09-08 22:08:02 +00:00
|
|
|
{-| Filters out Nothings and extracts the remaining values.
|
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
justs : [Maybe a] -> [a]
|
2013-07-25 22:07:07 +00:00
|
|
|
justs = foldr cons []
|