2 % (c) The AQUA Project, Glasgow University, 1994-1996
5 \section[Maybe]{Module @Maybe@}
8 {-# OPTIONS -fno-implicit-prelude #-}
12 the, exists, theExists, maybe, fromMaybe, listToMaybe, maybeToList,
13 findMaybe, catMaybes, mapMaybe, joinMaybe, unfoldr
16 import IOBase ( error )
17 import Monad ( filter )
23 %*********************************************************
25 \subsection{Functions}
27 %*********************************************************
30 maybe :: b -> (a -> b) -> Maybe a -> b
32 maybe n f (Just x) = f x
34 exists :: Maybe a -> Bool
35 exists = maybe False (const True)
38 the = maybe (error "Maybe.the: Nothing") id
40 theExists :: Maybe a -> (a, Bool)
41 theExists Nothing = (error "Maybe.theExists: Nothing", False)
42 theExists (Just x) = (x, True)
44 fromMaybe :: a -> Maybe a -> a
45 fromMaybe d = maybe d id
47 maybeToList :: Maybe a -> [a]
48 maybeToList = maybe [] (\ x -> [x])
50 listToMaybe :: [a] -> Maybe a
51 listToMaybe [] = Nothing
52 listToMaybe (a:as) = Just a
54 findMaybe :: (a -> Bool) -> [a] -> Maybe a
55 findMaybe p = listToMaybe . filter p
57 catMaybes :: [Maybe a] -> [a]
59 catMaybes (Nothing:xs) = catMaybes xs
60 catMaybes (Just x:xs) = x : catMaybes xs
62 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
63 mapMaybe f = catMaybes . map f
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)
71 -- unfoldr f' (foldr f z xs) == (xs,z)
73 -- if the following holds:
75 -- f' (f x y) = Just (x,y)
77 unfoldr :: (a -> Maybe (b, a)) -> a -> ([b],a)
80 Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')