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 PrelErr ( error )
24 import Monad ( filter )
31 %*********************************************************
33 \subsection{Functions}
35 %*********************************************************
38 isJust :: Maybe a -> Bool
39 isJust Nothing = False
42 fromJust :: Maybe a -> a
43 fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
46 fromMaybe :: a -> Maybe a -> a
47 fromMaybe d x = case x of {Nothing -> d;Just v -> v}
49 maybeToList :: Maybe a -> [a]
50 maybeToList Nothing = []
51 maybeToList (Just x) = [x]
53 listToMaybe :: [a] -> Maybe a
54 listToMaybe [] = Nothing
55 listToMaybe (a:_) = Just a
57 findMaybe :: (a -> Bool) -> [a] -> Maybe a
58 findMaybe p = listToMaybe . filter p
60 catMaybes :: [Maybe a] -> [a]
61 catMaybes ls = [x | Just x <- ls]
63 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
66 let rs = mapMaybe f xs in
71 --OLD: mapMaybe f = catMaybes . map f
72 -- new version is potentially more space efficient
75 joinMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
79 Just v1 -> case m2 of {Nothing -> m1; Just v2 -> Just (f v1 v2)}
81 {- OLD: Note: stricter than the above.
82 joinMaybe _ Nothing Nothing = Nothing
83 joinMaybe _ (Just g) Nothing = Just g
84 joinMaybe _ Nothing (Just g) = Just g
85 joinMaybe f (Just g) (Just h) = Just (f g h)
91 unfoldr f' (foldr f z xs) == (xs,z)
93 if the following holds:
95 f' (f x y) = Just (x,y)
100 unfoldr :: (a -> Maybe (b, a)) -> a -> ([b],a)
103 Just (y,x') -> let (ys,x'') = unfoldr f x' in (y:ys,x'')