1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : portable
12 -- The Maybe type, and associated operations.
14 -----------------------------------------------------------------------------
18 Maybe(Nothing,Just)-- instance of: Eq, Ord, Show, Read,
19 -- Functor, Monad, MonadPlus
21 , maybe -- :: b -> (a -> b) -> Maybe a -> b
23 , isJust -- :: Maybe a -> Bool
24 , isNothing -- :: Maybe a -> Bool
25 , fromJust -- :: Maybe a -> a
26 , fromMaybe -- :: a -> Maybe a -> a
27 , listToMaybe -- :: [a] -> Maybe a
28 , maybeToList -- :: Maybe a -> [a]
29 , catMaybes -- :: [Maybe a] -> [a]
30 , mapMaybe -- :: (a -> Maybe b) -> [a] -> [b]
33 #ifdef __GLASGOW_HASKELL__
34 import {-# SOURCE #-} GHC.Err ( error )
40 import Prelude (Maybe(..), maybe)
54 -- ---------------------------------------------------------------------------
55 -- The Maybe type, and instances
57 -- | The 'Maybe' type encapsulates an optional value. A value of type
58 -- @'Maybe' a@ either contains a value of type @a@ (represented as @'Just' a@),
59 -- or it is empty (represented as 'Nothing'). Using 'Maybe' is a good way to
60 -- deal with errors or exceptional cases without resorting to drastic
61 -- measures such as 'error'.
63 -- The 'Maybe' type is also a monad. It is a simple kind of error
64 -- monad, where all errors are represented by 'Nothing'. A richer
65 -- error monad can be built using the 'Data.Either.Either' type.
67 data Maybe a = Nothing | Just a
70 instance Functor Maybe where
71 fmap _ Nothing = Nothing
72 fmap f (Just a) = Just (f a)
74 instance Monad Maybe where
76 Nothing >>= _ = Nothing
79 Nothing >> _ = Nothing
84 -- ---------------------------------------------------------------------------
85 -- Functions over Maybe
87 maybe :: b -> (a -> b) -> Maybe a -> b
89 maybe _ f (Just x) = f x
92 isJust :: Maybe a -> Bool
93 isJust Nothing = False
96 isNothing :: Maybe a -> Bool
97 isNothing Nothing = True
100 fromJust :: Maybe a -> a
101 fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
102 fromJust (Just x) = x
104 fromMaybe :: a -> Maybe a -> a
105 fromMaybe d x = case x of {Nothing -> d;Just v -> v}
107 maybeToList :: Maybe a -> [a]
108 maybeToList Nothing = []
109 maybeToList (Just x) = [x]
111 listToMaybe :: [a] -> Maybe a
112 listToMaybe [] = Nothing
113 listToMaybe (a:_) = Just a
115 catMaybes :: [Maybe a] -> [a]
116 catMaybes ls = [x | Just x <- ls]
118 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
121 let rs = mapMaybe f xs in
126 #endif /* else not __NHC__ */