1acead784dd8907e59a5f54f7fcc924e4a8d865b
[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 {-# OPTIONS -fno-implicit-prelude #-}
9
10 module Maybe(
11     Maybe(..),
12     the, exists, theExists, maybe, fromMaybe, listToMaybe, maybeToList,
13     findMaybe, catMaybes, mapMaybe, joinMaybe, unfoldr
14   ) where
15
16 import IOBase   ( error )
17 import Monad    ( filter )
18 import PrelList
19 import PrelBase
20 \end{code}
21
22
23 %*********************************************************
24 %*                                                      *
25 \subsection{Functions}
26 %*                                                      *
27 %*********************************************************
28
29 \begin{code}
30 maybe                   :: b -> (a -> b) -> Maybe a -> b
31 maybe n f Nothing       =  n
32 maybe n f (Just x)      =  f x
33
34 exists                 :: Maybe a -> Bool
35 exists                 =  maybe False (const True)
36
37 the                    :: Maybe a -> a
38 the                    =  maybe (error "Maybe.the: Nothing") id
39
40 theExists              :: Maybe a -> (a, Bool)
41 theExists Nothing      =  (error "Maybe.theExists: Nothing", False)
42 theExists (Just x)     =  (x, True)
43
44 fromMaybe              :: a -> Maybe a -> a
45 fromMaybe d            =  maybe d id
46
47 maybeToList            :: Maybe a -> [a]
48 maybeToList            =  maybe [] (\ x -> [x])
49
50 listToMaybe            :: [a] -> Maybe a
51 listToMaybe []         =  Nothing
52 listToMaybe (a:as)     =  Just a
53  
54 findMaybe              :: (a -> Bool) -> [a] -> Maybe a
55 findMaybe p            =  listToMaybe . filter p
56
57 catMaybes              :: [Maybe a] -> [a]
58 catMaybes []           =  []
59 catMaybes (Nothing:xs) =  catMaybes xs
60 catMaybes (Just x:xs)  =  x : catMaybes xs
61
62 mapMaybe               :: (a -> Maybe b) -> [a] -> [b]
63 mapMaybe f             =  catMaybes . map f
64
65 joinMaybe              :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a 
66 joinMaybe _ Nothing  Nothing  = Nothing
67 joinMaybe _ (Just g) Nothing  = Just g
68 joinMaybe _ Nothing  (Just g) = Just g
69 joinMaybe f (Just g) (Just h) = Just (f g h)
70
71 --    unfoldr f' (foldr f z xs) == (xs,z)
72 --
73 -- if the following holds:
74 --
75 --    f' (f x y) = Just (x,y)
76 --    f' z       = Nothing
77 unfoldr                :: (a -> Maybe (b, a)) -> a -> ([b],a)
78 unfoldr f x =
79   case f x of
80   Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')
81   Nothing     -> ([],x)
82 \end{code}