[project @ 1997-03-17 20:34:25 by simonpj]
[ghc-hetmet.git] / ghc / lib / required / 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 IOBase   ( error )
24 import Monad    ( filter )
25 import PrelList
26 import PrelBase
27 \end{code}
28
29
30 %*********************************************************
31 %*                                                      *
32 \subsection{Functions}
33 %*                                                      *
34 %*********************************************************
35
36 \begin{code}
37 isJust         :: Maybe a -> Bool
38 isJust Nothing = False
39 isJust _       = True
40
41 fromJust          :: Maybe a -> a
42 fromJust Nothing  = error "Maybe.fromJust: Nothing" -- yuck
43 fromJust (Just x) = x
44
45 fromMaybe     :: a -> Maybe a -> a
46 fromMaybe d x = case x of {Nothing -> d;Just v  -> v}
47
48 maybeToList            :: Maybe a -> [a]
49 maybeToList  Nothing   = []
50 maybeToList  (Just x)  = [x]
51
52 listToMaybe           :: [a] -> Maybe a
53 listToMaybe []        =  Nothing
54 listToMaybe (a:_)     =  Just a
55  
56 findMaybe              :: (a -> Bool) -> [a] -> Maybe a
57 findMaybe p            =  listToMaybe . filter p
58
59 catMaybes              :: [Maybe a] -> [a]
60 catMaybes ls = [x | Just x <- ls]
61
62 mapMaybe          :: (a -> Maybe b) -> [a] -> [b]
63 mapMaybe f []     = []
64 mapMaybe f (x:xs) =
65  let rs = mapMaybe f xs in
66  case f x of
67   Nothing -> rs
68   Just r  -> r:rs
69
70 --OLD: mapMaybe f             =  catMaybes . map f
71 -- new version is potentially more space efficient
72
73 -- Not exported
74 joinMaybe         :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a 
75 joinMaybe f m1 m2 =
76  case m1 of
77   Nothing -> m2
78   Just v1 -> case m2 of {Nothing -> m1; Just v2 -> Just (f v1 v2)}
79
80 {- OLD: Note: stricter than the above.
81 joinMaybe _ Nothing  Nothing  = Nothing
82 joinMaybe _ (Just g) Nothing  = Just g
83 joinMaybe _ Nothing  (Just g) = Just g
84 joinMaybe f (Just g) (Just h) = Just (f g h)
85 -}
86
87 \end{code}
88
89 \begin{verbatim}
90   unfoldr f' (foldr f z xs) == (xs,z)
91
92  if the following holds:
93
94    f' (f x y) = Just (x,y)
95    f' z       = Nothing
96 \end{verbatim}
97
98 \begin{code}
99 unfoldr       :: (a -> Maybe (b, a)) -> a -> ([b],a)
100 unfoldr f x   =
101   case f x of
102   Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')
103   Nothing     -> ([],x)
104 \end{code}