[project @ 2001-06-28 14:15:04 by simonmar]
[packages/pretty.git] / Data / Maybe.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 --
4 -- Module : Data.Maybe
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/core/LICENSE)
7 --
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : non-portable
11 --
12 -- $Id: Maybe.hs,v 1.1 2001/06/28 14:15:02 simonmar Exp $
13 --
14 -- The Maybe type, and associated operations.
15 --
16 -----------------------------------------------------------------------------
17
18 module Data.Maybe
19 (
20 Maybe(Nothing,Just)-- instance of: Eq, Ord, Show, Read,
21 -- Functor, Monad, MonadPlus
22
23 , maybe -- :: b -> (a -> b) -> Maybe a -> b
24
25 , isJust -- :: Maybe a -> Bool
26 , isNothing -- :: Maybe a -> Bool
27 , fromJust -- :: Maybe a -> a
28 , fromMaybe -- :: a -> Maybe a -> a
29 , listToMaybe -- :: [a] -> Maybe a
30 , maybeToList -- :: Maybe a -> [a]
31 , catMaybes -- :: [Maybe a] -> [a]
32 , mapMaybe -- :: (a -> Maybe b) -> [a] -> [b]
33 ) where
34
35 #ifdef __GLASGOW_HASKELL__
36 import GHC.Err ( error )
37 import GHC.List
38 import GHC.Maybe
39 import GHC.Base
40 #endif
41
42 isJust :: Maybe a -> Bool
43 isJust Nothing = False
44 isJust _ = True
45
46 isNothing :: Maybe a -> Bool
47 isNothing Nothing = True
48 isNothing _ = False
49
50 fromJust :: Maybe a -> a
51 fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
52 fromJust (Just x) = x
53
54 fromMaybe :: a -> Maybe a -> a
55 fromMaybe d x = case x of {Nothing -> d;Just v -> v}
56
57 maybeToList :: Maybe a -> [a]
58 maybeToList Nothing = []
59 maybeToList (Just x) = [x]
60
61 listToMaybe :: [a] -> Maybe a
62 listToMaybe [] = Nothing
63 listToMaybe (a:_) = Just a
64
65 catMaybes :: [Maybe a] -> [a]
66 catMaybes ls = [x | Just x <- ls]
67
68 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
69 mapMaybe _ [] = []
70 mapMaybe f (x:xs) =
71 let rs = mapMaybe f xs in
72 case f x of
73 Nothing -> rs
74 Just r -> r:rs
75