[project @ 1996-12-19 18:35:23 by simonpj]
[ghc-hetmet.git] / ghc / lib / required / Maybe.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4
5 \section[Maybe]{Module @Maybe@}
6
7 \begin{code}
8 module Maybe(
9     Maybe(..),
10     the, exists, theExists, maybe, fromMaybe, listToMaybe, maybeToList,
11     findMaybe, catMaybes, mapMaybe, joinMaybe, unfoldr
12   ) where
13
14 import Prelude  ()
15 import IOBase   ( error )
16 import Monad    ( filter )
17 import PrelList
18 import PrelBase
19 \end{code}
20
21
22 %*********************************************************
23 %*                                                      *
24 \subsection{Functions}
25 %*                                                      *
26 %*********************************************************
27
28 \begin{code}
29 maybe                   :: b -> (a -> b) -> Maybe a -> b
30 maybe n f Nothing       =  n
31 maybe n f (Just x)      =  f x
32
33 exists                 :: Maybe a -> Bool
34 exists                 =  maybe False (const True)
35
36 the                    :: Maybe a -> a
37 the                    =  maybe (error "Maybe.the: Nothing") id
38
39 theExists              :: Maybe a -> (a, Bool)
40 theExists Nothing      =  (error "Maybe.theExists: Nothing", False)
41 theExists (Just x)     =  (x, True)
42
43 fromMaybe              :: a -> Maybe a -> a
44 fromMaybe d            =  maybe d id
45
46 maybeToList            :: Maybe a -> [a]
47 maybeToList            =  maybe [] (\ x -> [x])
48
49 listToMaybe            :: [a] -> Maybe a
50 listToMaybe []         =  Nothing
51 listToMaybe (a:as)     =  Just a
52  
53 findMaybe              :: (a -> Bool) -> [a] -> Maybe a
54 findMaybe p            =  listToMaybe . filter p
55
56 catMaybes              :: [Maybe a] -> [a]
57 catMaybes []           =  []
58 catMaybes (Nothing:xs) =  catMaybes xs
59 catMaybes (Just x:xs)  =  x : catMaybes xs
60
61 mapMaybe               :: (a -> Maybe b) -> [a] -> [b]
62 mapMaybe f             =  catMaybes . map f
63
64 joinMaybe              :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a 
65 joinMaybe _ Nothing  Nothing  = Nothing
66 joinMaybe _ (Just g) Nothing  = Just g
67 joinMaybe _ Nothing  (Just g) = Just g
68 joinMaybe f (Just g) (Just h) = Just (f g h)
69
70 --    unfoldr f' (foldr f z xs) == (xs,z)
71 --
72 -- if the following holds:
73 --
74 --    f' (f x y) = Just (x,y)
75 --    f' z       = Nothing
76 unfoldr                :: (a -> Maybe (b, a)) -> a -> ([b],a)
77 unfoldr f x =
78   case f x of
79   Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')
80   Nothing     -> ([],x)
81 \end{code}