2 % (c) The AQUA Project, Glasgow University, 1994-1996
5 \section[Maybe]{Module @Maybe@}
10 the, exists, theExists, maybe, fromMaybe, listToMaybe, maybeToList,
11 findMaybe, catMaybes, mapMaybe, joinMaybe, unfoldr
15 import IOBase ( error )
16 import Monad ( filter )
22 %*********************************************************
24 \subsection{Functions}
26 %*********************************************************
29 maybe :: b -> (a -> b) -> Maybe a -> b
31 maybe n f (Just x) = f x
33 exists :: Maybe a -> Bool
34 exists = maybe False (const True)
37 the = maybe (error "Maybe.the: Nothing") id
39 theExists :: Maybe a -> (a, Bool)
40 theExists Nothing = (error "Maybe.theExists: Nothing", False)
41 theExists (Just x) = (x, True)
43 fromMaybe :: a -> Maybe a -> a
44 fromMaybe d = maybe d id
46 maybeToList :: Maybe a -> [a]
47 maybeToList = maybe [] (\ x -> [x])
49 listToMaybe :: [a] -> Maybe a
50 listToMaybe [] = Nothing
51 listToMaybe (a:as) = Just a
53 findMaybe :: (a -> Bool) -> [a] -> Maybe a
54 findMaybe p = listToMaybe . filter p
56 catMaybes :: [Maybe a] -> [a]
58 catMaybes (Nothing:xs) = catMaybes xs
59 catMaybes (Just x:xs) = x : catMaybes xs
61 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
62 mapMaybe f = catMaybes . map f
64 joinMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
65 joinMaybe _ Nothing Nothing = Nothing
66 joinMaybe _ (Just g) Nothing = Just g
67 joinMaybe _ Nothing (Just g) = Just g
68 joinMaybe f (Just g) (Just h) = Just (f g h)
70 -- unfoldr f' (foldr f z xs) == (xs,z)
72 -- if the following holds:
74 -- f' (f x y) = Just (x,y)
76 unfoldr :: (a -> Maybe (b, a)) -> a -> ([b],a)
79 Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')