3c86e9148ee06273678c9cc39781663822e3addf
[ghc-hetmet.git] / ghc / lib / std / Maybe.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4 \section[Maybe]{Module @Maybe@}
5
6 The standard Haskell 1.3 library for working with
7 @Maybe@ values.
8
9 \begin{code}
10 {-# OPTIONS -fno-implicit-prelude #-}
11
12 module Maybe
13    (
14     Maybe(..),
15     isJust, fromJust, 
16     fromMaybe, 
17     listToMaybe, maybeToList,
18     catMaybes, 
19     mapMaybe, 
20     unfoldr
21    ) where
22
23 import PrelErr  ( error )
24 import Monad    ( filter )
25 import PrelList
26 import PrelMaybe
27 import PrelBase
28 \end{code}
29
30
31 %*********************************************************
32 %*                                                      *
33 \subsection{Functions}
34 %*                                                      *
35 %*********************************************************
36
37 \begin{code}
38 isJust         :: Maybe a -> Bool
39 isJust Nothing = False
40 isJust _       = True
41
42 fromJust          :: Maybe a -> a
43 fromJust Nothing  = error "Maybe.fromJust: Nothing" -- yuck
44 fromJust (Just x) = x
45
46 fromMaybe     :: a -> Maybe a -> a
47 fromMaybe d x = case x of {Nothing -> d;Just v  -> v}
48
49 maybeToList            :: Maybe a -> [a]
50 maybeToList  Nothing   = []
51 maybeToList  (Just x)  = [x]
52
53 listToMaybe           :: [a] -> Maybe a
54 listToMaybe []        =  Nothing
55 listToMaybe (a:_)     =  Just a
56  
57 findMaybe              :: (a -> Bool) -> [a] -> Maybe a
58 findMaybe p            =  listToMaybe . filter p
59
60 catMaybes              :: [Maybe a] -> [a]
61 catMaybes ls = [x | Just x <- ls]
62
63 mapMaybe          :: (a -> Maybe b) -> [a] -> [b]
64 mapMaybe f []     = []
65 mapMaybe f (x:xs) =
66  let rs = mapMaybe f xs in
67  case f x of
68   Nothing -> rs
69   Just r  -> r:rs
70
71 --OLD: mapMaybe f             =  catMaybes . map f
72 -- new version is potentially more space efficient
73
74 -- Not exported
75 joinMaybe         :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a 
76 joinMaybe f m1 m2 =
77  case m1 of
78   Nothing -> m2
79   Just v1 -> case m2 of {Nothing -> m1; Just v2 -> Just (f v1 v2)}
80
81 {- OLD: Note: stricter than the above.
82 joinMaybe _ Nothing  Nothing  = Nothing
83 joinMaybe _ (Just g) Nothing  = Just g
84 joinMaybe _ Nothing  (Just g) = Just g
85 joinMaybe f (Just g) (Just h) = Just (f g h)
86 -}
87
88 \end{code}
89
90 \begin{verbatim}
91   unfoldr f' (foldr f z xs) == (xs,z)
92
93  if the following holds:
94
95    f' (f x y) = Just (x,y)
96    f' z       = Nothing
97 \end{verbatim}
98
99 \begin{code}
100 unfoldr       :: (a -> Maybe (b, a)) -> a -> ([b],a)
101 unfoldr f x   =
102   case f x of
103   Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')
104   Nothing     -> ([],x)
105 \end{code}