1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/core/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 )
38 -- ---------------------------------------------------------------------------
39 -- The Maybe type, and instances
41 data Maybe a = Nothing | Just a deriving (Eq, Ord)
43 instance Functor Maybe where
44 fmap _ Nothing = Nothing
45 fmap f (Just a) = Just (f a)
47 instance Monad Maybe where
49 Nothing >>= _ = Nothing
52 Nothing >> _ = Nothing
57 -- ---------------------------------------------------------------------------
58 -- Functions over Maybe
60 maybe :: b -> (a -> b) -> Maybe a -> b
62 maybe _ f (Just x) = f x
64 isJust :: Maybe a -> Bool
65 isJust Nothing = False
68 isNothing :: Maybe a -> Bool
69 isNothing Nothing = True
72 fromJust :: Maybe a -> a
73 fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
76 fromMaybe :: a -> Maybe a -> a
77 fromMaybe d x = case x of {Nothing -> d;Just v -> v}
79 maybeToList :: Maybe a -> [a]
80 maybeToList Nothing = []
81 maybeToList (Just x) = [x]
83 listToMaybe :: [a] -> Maybe a
84 listToMaybe [] = Nothing
85 listToMaybe (a:_) = Just a
87 catMaybes :: [Maybe a] -> [a]
88 catMaybes ls = [x | Just x <- ls]
90 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
93 let rs = mapMaybe f xs in