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
|
2013-10-18 03:54:55 +00:00
|
|
|
@docs justs
|
2013-09-08 22:08:02 +00:00
|
|
|
-}
|
|
|
|
|
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
|
2013-10-18 03:54:55 +00:00
|
|
|
result in a value (e.g. logarithm is defined only for positive
|
|
|
|
numbers).
|
2013-09-08 22:08:02 +00:00
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
data Maybe a = Just a | Nothing
|
|
|
|
|
2014-02-18 23:06:14 +00:00
|
|
|
{-| Provide a default value and a function to extract the contents of a `Maybe`.
|
|
|
|
When given `Nothing` you get the default, when given a `Just` you apply the
|
|
|
|
function to the associated value.
|
|
|
|
|
|
|
|
isPositive : Maybe Int -> Bool
|
|
|
|
isPositive maybeInt = maybe False (\n -> n > 0) maybeInt
|
|
|
|
|
|
|
|
map : (a -> b) -> Maybe a -> Maybe b
|
|
|
|
map f m = maybe Nothing (\x -> Just (f x)) m
|
2013-09-08 22:08:02 +00:00
|
|
|
-}
|
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
|
|
|
|
|
2014-02-18 23:06:14 +00:00
|
|
|
{-| Check if a maybe happens to be a `Just`.
|
|
|
|
|
|
|
|
isJust (Just 42) == True
|
|
|
|
isJust (Just []) == True
|
|
|
|
isJust Nothing == False
|
2013-09-08 22:08:02 +00:00
|
|
|
-}
|
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`.
|
2014-02-18 23:06:14 +00:00
|
|
|
|
|
|
|
isNothing (Just 42) == False
|
|
|
|
isNothing (Just []) == False
|
|
|
|
isNothing Nothing == True
|
2013-09-08 22:08:02 +00:00
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
isNothing : Maybe a -> Bool
|
|
|
|
isNothing = not . isJust
|
|
|
|
|
2014-02-18 23:06:14 +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.
|
2014-02-18 23:06:14 +00:00
|
|
|
|
|
|
|
justs [Just 0, Nothing, Just 5, Just 7] == [0,5,7]
|
2013-09-08 22:08:02 +00:00
|
|
|
-}
|
2013-02-27 07:26:28 +00:00
|
|
|
justs : [Maybe a] -> [a]
|
2013-07-25 22:07:07 +00:00
|
|
|
justs = foldr cons []
|