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 )
39 -- ---------------------------------------------------------------------------
40 -- The Maybe type, and instances
42 -- | The 'Maybe' type encapsulates an optional value. A value of type
43 -- @'Maybe' a@ either contains a value of type @a@ (represented as @'Just' a@),
44 -- or it is empty (represented as 'Nothing'). Using 'Maybe' is a good way to
45 -- deal with errors or exceptional cases without resorting to drastic
46 -- measures such as 'error'.
48 -- The 'Maybe' type is also a monad. It is a simple kind of error
49 -- monad, where all errors are represented by 'Nothing'. A richer
50 -- error monad can be built using the 'Data.Either.Either' type.
52 data Maybe a = Nothing | Just a
55 instance Functor Maybe where
56 fmap _ Nothing = Nothing
57 fmap f (Just a) = Just (f a)
59 instance Monad Maybe where
61 Nothing >>= _ = Nothing
64 Nothing >> _ = Nothing
69 -- ---------------------------------------------------------------------------
70 -- Functions over Maybe
72 maybe :: b -> (a -> b) -> Maybe a -> b
74 maybe _ f (Just x) = f x
77 isJust :: Maybe a -> Bool
78 isJust Nothing = False
81 isNothing :: Maybe a -> Bool
82 isNothing Nothing = True
85 fromJust :: Maybe a -> a
86 fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
89 fromMaybe :: a -> Maybe a -> a
90 fromMaybe d x = case x of {Nothing -> d;Just v -> v}
92 maybeToList :: Maybe a -> [a]
93 maybeToList Nothing = []
94 maybeToList (Just x) = [x]
96 listToMaybe :: [a] -> Maybe a
97 listToMaybe [] = Nothing
98 listToMaybe (a:_) = Just a
100 catMaybes :: [Maybe a] -> [a]
101 catMaybes ls = [x | Just x <- ls]
103 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
106 let rs = mapMaybe f xs in