[project @ 2003-04-04 14:36:31 by simonpj]
[ghc-base.git] / Data / Maybe.hs
index de5d121..195daab 100644 (file)
@@ -1,16 +1,14 @@
 {-# OPTIONS -fno-implicit-prelude #-}
 -----------------------------------------------------------------------------
--- 
+-- |
 -- Module      :  Data.Maybe
 -- Copyright   :  (c) The University of Glasgow 2001
--- License     :  BSD-style (see the file libraries/core/LICENSE)
+-- License     :  BSD-style (see the file libraries/base/LICENSE)
 -- 
 -- Maintainer  :  libraries@haskell.org
 -- Stability   :  experimental
 -- Portability :  portable
 --
--- $Id: Maybe.hs,v 1.2 2001/07/03 11:37:50 simonmar Exp $
---
 -- The Maybe type, and associated operations.
 --
 -----------------------------------------------------------------------------
@@ -33,12 +31,64 @@ module Data.Maybe
    ) where
 
 #ifdef __GLASGOW_HASKELL__
-import GHC.Err ( error )
-import GHC.List
-import GHC.Maybe
+import {-# SOURCE #-} GHC.Err ( error )
 import GHC.Base
 #endif
 
+#ifdef __NHC__
+import Prelude
+import Prelude (Maybe(..), maybe)
+import Maybe
+    ( isJust
+    , isNothing
+    , fromJust
+    , fromMaybe
+    , listToMaybe
+    , maybeToList 
+    , catMaybes
+    , mapMaybe
+    )
+#else
+
+#ifndef __HUGS__
+-- ---------------------------------------------------------------------------
+-- The Maybe type, and instances
+
+-- | The 'Maybe' type encapsulates an optional value.  A value of type
+-- @'Maybe' a@ either contains a value of type @a@ (represented as @'Just' a@), 
+-- or it is empty (represented as 'Nothing').  Using 'Maybe' is a good way to 
+-- deal with errors or exceptional cases without resorting to drastic
+-- measures such as 'error'.
+--
+-- The 'Maybe' type is also a monad.  It is a simple kind of error
+-- monad, where all errors are represented by 'Nothing'.  A richer
+-- error monad can be built using the 'Data.Either.Either' type.
+
+data  Maybe a  =  Nothing | Just a     
+  deriving (Eq, Ord)
+
+instance  Functor Maybe  where
+    fmap _ Nothing       = Nothing
+    fmap f (Just a)      = Just (f a)
+
+instance  Monad Maybe  where
+    (Just x) >>= k      = k x
+    Nothing  >>= _      = Nothing
+
+    (Just _) >>  k      = k
+    Nothing  >>  _      = Nothing
+
+    return              = Just
+    fail _             = Nothing
+
+-- ---------------------------------------------------------------------------
+-- Functions over Maybe
+
+maybe :: b -> (a -> b) -> Maybe a -> b
+maybe n _ Nothing  = n
+maybe _ f (Just x) = f x
+#endif  /* __HUGS__ */
+
 isJust         :: Maybe a -> Bool
 isJust Nothing = False
 isJust _       = True
@@ -73,3 +123,4 @@ mapMaybe f (x:xs) =
   Nothing -> rs
   Just r  -> r:rs
 
+#endif /* else not __NHC__ */