[project @ 2001-07-03 11:37:49 by simonmar]
[ghc-base.git] / GHC / Maybe.lhs
1 % ------------------------------------------------------------------------------
2 % $Id: Maybe.lhs,v 1.1 2001/06/28 14:15:03 simonmar Exp $
3 %
4 % (c) The University of Glasgow, 1992-2000
5 %
6
7 \section[GHC.Maybe]{Module @GHC.Maybe@}
8
9 The @Maybe@ type.
10
11 \begin{code}
12 {-# OPTIONS -fno-implicit-prelude #-}
13
14 module GHC.Maybe where
15
16 import GHC.Base
17 \end{code}
18
19 %*********************************************************
20 %*                                                      *
21 \subsection{Maybe type}
22 %*                                                      *
23 %*********************************************************
24
25 \begin{code}
26 data  Maybe a  =  Nothing | Just a      deriving (Eq, Ord)
27
28 maybe :: b -> (a -> b) -> Maybe a -> b
29 maybe n _ Nothing  = n
30 maybe _ f (Just x) = f x
31
32 instance  Functor Maybe  where
33     fmap _ Nothing       = Nothing
34     fmap f (Just a)      = Just (f a)
35
36 instance  Monad Maybe  where
37     (Just x) >>= k      = k x
38     Nothing  >>= _      = Nothing
39
40     (Just _) >>  k      = k
41     Nothing  >>  _      = Nothing
42
43     return              = Just
44     fail _              = Nothing
45 \end{code}
46
47
48 %*********************************************************
49 %*                                                      *
50 \subsection{Either type}
51 %*                                                      *
52 %*********************************************************
53
54 \begin{code}
55 data  Either a b  =  Left a | Right b   deriving (Eq, Ord )
56
57 either                  :: (a -> c) -> (b -> c) -> Either a b -> c
58 either f _ (Left x)     =  f x
59 either _ g (Right y)    =  g y
60 \end{code}
61
62
63
64