6 Maybe Utilities


module Maybe(
    the, exists, theExists, maybe, fromMaybe, listToMaybe, maybeToList,
    findMaybe, catMaybes, mapMaybe, joinMaybe, unfoldr ) where

exists               :: Maybe a -> Bool
the                  :: Maybe a -> a
theExists            :: Maybe a -> (a, Bool)
fromMaybe            :: a -> Maybe a -> a
listToMaybe          :: [a] -> Maybe a
maybeToList          :: Maybe a -> [a]
findMaybe            :: (a -> Bool) -> [a] -> Maybe a
catMaybes            :: [Maybe a] -> [a]
mapMaybe             :: (a -> Maybe b) -> [a] -> [b]
joinMaybe            :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a 
unfoldr              :: (a -> Maybe (b, a)) -> a -> ([b],a)

These utilities are self-documenting. Other operations on Maybe are part of the monadic classes in the Prelude.

6.1 Library Maybe


module Maybe(
    the, exists, theExists, maybe, fromMaybe, listToMaybe, maybeToList,
    findMaybe, catMaybes, mapMaybe, joinMaybe, unfoldr ) where

exists                 :: Maybe a -> Bool
exists                 =  maybe False (const True)

the                    :: Maybe a -> a
the                    =  maybe (error "Maybe.the: Nothing") id

theExists              :: Maybe a -> (a, Bool)
theExists              =  maybe (error "Maybe.theExists: Nothing", False) (a, True)

fromMaybe              :: a -> Maybe a -> a
fromMaybe d            =  maybe d id

maybeToList            :: Maybe a -> [a]
maybeToList            =  maybe [] (\ x -> [x])

listToMaybe            :: [a] -> Maybe a
listToMaybe []         =  Nothing
listToMaybe (a:as)     =  Just a

findMaybe              :: (a -> Bool) -> [a] -> Maybe a
findMaybe p            =  listToMaybe . filter p

catMaybes              :: [Maybe a] -> [a]
catMaybes []           =  []
catMaybes (Nothing:xs) =  catMaybes xs
catMaybes (Just x:xs)  =  x : catMaybes xs

mapMaybe               :: (a -> Maybe b) -> [a] -> [b]
mapMaybe f             =  catMaybes . map f

joinMaybe              :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a 
joinMaybe _ Nothing  Nothing  = Nothing
joinMaybe _ (Just g) Nothing  = Just g
joinMaybe _ Nothing  (Just g) = Just g
joinMaybe f (Just g) (Just h) = Just (f g h)

--    unfoldr f' (foldr f z xs) == (xs,z)
--
-- if the following holds:
--
--    f' (f x y) = Just (x,y)
--    f' z       = Nothing
unfoldr                :: (a -> Maybe (b, a)) -> a -> ([b],a)
unfoldr f x =
  case f x of
  Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')
  Nothing     -> ([],x)

Next section: Char
The Haskell 1.3 Library Report