[project @ 2003-04-11 11:10:57 by ross]
[ghc-base.git] / Data / Monoid.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Monoid
4 -- Copyright   :  (c) Andy Gill 2001,
5 --                (c) Oregon Graduate Institute of Science and Technology, 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  experimental
10 -- Portability :  non-portable (requires extended type classes)
11 --
12 -- Declaration of the Monoid class, and instances for list and functions.
13 --
14 --        Inspired by the paper
15 --        /Functional Programming with Overloading and
16 --            Higher-Order Polymorphism/, 
17 --          Mark P Jones (<http://www.cse.ogi.edu/~mpj/>)
18 --                Advanced School of Functional Programming, 1995.
19 -----------------------------------------------------------------------------
20
21 module Data.Monoid (
22         Monoid(..)
23   ) where
24
25 import Prelude
26
27 -- ---------------------------------------------------------------------------
28 -- | The monoid class.
29 -- A minimal complete definition must supply 'mempty' and 'mappend',
30 -- and these should satisfy the monoid laws.
31
32 class Monoid a where
33         mempty  :: a
34         -- ^ Identity of 'mappend'
35         mappend :: a -> a -> a
36         -- ^ An associative operation
37         mconcat :: [a] -> a
38
39         -- ^ Fold a list using the monoid.
40         -- For most types, the default definition for 'mconcat' will be
41         -- used, but the function is included in the class definition so
42         -- that an optimized version can be provided for specific types.
43
44         mconcat = foldr mappend mempty
45
46 -- Monoid instances.
47
48 instance Monoid [a] where
49         mempty  = []
50         mappend = (++)
51
52 instance Monoid (a -> a) where
53         mempty  = id
54         mappend = (.)
55
56 instance Monoid () where
57         -- Should it be strict?
58         mempty        = ()
59         _ `mappend` _ = ()
60         mconcat _     = ()