2 % (c) The AQUA Project, Glasgow University, 1994-1996
4 \section[Maybe]{Module @Maybe@}
6 The standard Haskell 1.3 library for working with
10 {-# OPTIONS -fno-implicit-prelude #-}
17 listToMaybe, maybeToList,
23 import IOBase ( error )
24 import Monad ( filter )
30 %*********************************************************
32 \subsection{Functions}
34 %*********************************************************
37 isJust :: Maybe a -> Bool
38 isJust Nothing = False
41 fromJust :: Maybe a -> a
42 fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
45 fromMaybe :: a -> Maybe a -> a
46 fromMaybe d x = case x of {Nothing -> d;Just v -> v}
48 maybeToList :: Maybe a -> [a]
49 maybeToList Nothing = []
50 maybeToList (Just x) = [x]
52 listToMaybe :: [a] -> Maybe a
53 listToMaybe [] = Nothing
54 listToMaybe (a:_) = Just a
56 findMaybe :: (a -> Bool) -> [a] -> Maybe a
57 findMaybe p = listToMaybe . filter p
59 catMaybes :: [Maybe a] -> [a]
60 catMaybes ls = [x | Just x <- ls]
62 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
65 let rs = mapMaybe f xs in
70 --OLD: mapMaybe f = catMaybes . map f
71 -- new version is potentially more space efficient
74 joinMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
78 Just v1 -> case m2 of {Nothing -> m1; Just v2 -> Just (f v1 v2)}
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)
90 unfoldr f' (foldr f z xs) == (xs,z)
92 if the following holds:
94 f' (f x y) = Just (x,y)
99 unfoldr :: (a -> Maybe (b, a)) -> a -> ([b],a)
102 Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')