[project @ 1996-12-19 18:07:39 by simonpj]
[ghc-hetmet.git] / ghc / lib / required / Maybe.hs
1 module Maybe(
2     the, exists, theExists, maybe, fromMaybe, listToMaybe, maybeToList,
3     findMaybe, catMaybes, mapMaybe, joinMaybe, unfoldr ) where
4
5 exists                 :: Maybe a -> Bool
6 exists                 =  maybe False (const True)
7
8 the                    :: Maybe a -> a
9 the                    =  maybe (error "Maybe.the: Nothing") id
10
11 theExists              :: Maybe a -> (a, Bool)
12 theExists Nothing      =  (error "Maybe.theExists: Nothing", False)
13 theExists (Just x)     =  (x, True)
14
15 fromMaybe              :: a -> Maybe a -> a
16 fromMaybe d            =  maybe d id
17
18 maybeToList            :: Maybe a -> [a]
19 maybeToList            =  maybe [] (\ x -> [x])
20
21 listToMaybe            :: [a] -> Maybe a
22 listToMaybe []         =  Nothing
23 listToMaybe (a:as)     =  Just a
24  
25 findMaybe              :: (a -> Bool) -> [a] -> Maybe a
26 findMaybe p            =  listToMaybe . filter p
27
28 catMaybes              :: [Maybe a] -> [a]
29 catMaybes []           =  []
30 catMaybes (Nothing:xs) =  catMaybes xs
31 catMaybes (Just x:xs)  =  x : catMaybes xs
32
33 mapMaybe               :: (a -> Maybe b) -> [a] -> [b]
34 mapMaybe f             =  catMaybes . map f
35
36 joinMaybe              :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a 
37 joinMaybe _ Nothing  Nothing  = Nothing
38 joinMaybe _ (Just g) Nothing  = Just g
39 joinMaybe _ Nothing  (Just g) = Just g
40 joinMaybe f (Just g) (Just h) = Just (f g h)
41
42 --    unfoldr f' (foldr f z xs) == (xs,z)
43 --
44 -- if the following holds:
45 --
46 --    f' (f x y) = Just (x,y)
47 --    f' z       = Nothing
48 unfoldr                :: (a -> Maybe (b, a)) -> a -> ([b],a)
49 unfoldr f x =
50   case f x of
51   Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')
52   Nothing     -> ([],x)