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 -- $Id: Maybe.hs,v 1.3 2001/07/03 14:13:32 simonmar Exp $
14 -- The Maybe type, and associated operations.
16 -----------------------------------------------------------------------------
20 Maybe(Nothing,Just)-- instance of: Eq, Ord, Show, Read,
21 -- Functor, Monad, MonadPlus
23 , maybe -- :: b -> (a -> b) -> Maybe a -> b
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]
35 #ifdef __GLASGOW_HASKELL__
36 import {-# SOURCE #-} GHC.Err ( error )
40 -- ---------------------------------------------------------------------------
41 -- The Maybe type, and instances
43 data Maybe a = Nothing | Just a deriving (Eq, Ord)
45 instance Functor Maybe where
46 fmap _ Nothing = Nothing
47 fmap f (Just a) = Just (f a)
49 instance Monad Maybe where
51 Nothing >>= _ = Nothing
54 Nothing >> _ = Nothing
59 -- ---------------------------------------------------------------------------
60 -- Functions over Maybe
62 maybe :: b -> (a -> b) -> Maybe a -> b
64 maybe _ f (Just x) = f x
66 isJust :: Maybe a -> Bool
67 isJust Nothing = False
70 isNothing :: Maybe a -> Bool
71 isNothing Nothing = True
74 fromJust :: Maybe a -> a
75 fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
78 fromMaybe :: a -> Maybe a -> a
79 fromMaybe d x = case x of {Nothing -> d;Just v -> v}
81 maybeToList :: Maybe a -> [a]
82 maybeToList Nothing = []
83 maybeToList (Just x) = [x]
85 listToMaybe :: [a] -> Maybe a
86 listToMaybe [] = Nothing
87 listToMaybe (a:_) = Just a
89 catMaybes :: [Maybe a] -> [a]
90 catMaybes ls = [x | Just x <- ls]
92 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
95 let rs = mapMaybe f xs in