1 -----------------------------------------------------------------------------
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)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : non-portable (requires extended type classes)
12 -- Declaration of the Monoid class, and instances for list and functions.
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 -----------------------------------------------------------------------------
27 -- ---------------------------------------------------------------------------
28 -- | The monoid class.
29 -- A minimal complete definition must supply 'mempty' and 'mappend',
30 -- and these should satisfy the monoid laws.
34 -- ^ Identity of 'mappend'
35 mappend :: a -> a -> a
36 -- ^ An associative operation
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.
44 mconcat = foldr mappend mempty
48 instance Monoid [a] where
52 instance Monoid (a -> a) where
56 instance Monoid () where
57 -- Should it be strict?
62 instance (Monoid a, Monoid b) => Monoid (a,b) where
63 mempty = (mempty, mempty)
64 (a1,b1) `mappend` (a2,b2) =
65 (a1 `mappend` a2, b1 `mappend` b2)
67 instance (Monoid a, Monoid b, Monoid c) => Monoid (a,b,c) where
68 mempty = (mempty, mempty, mempty)
69 (a1,b1,c1) `mappend` (a2,b2,c2) =
70 (a1 `mappend` a2, b1 `mappend` b2, c1 `mappend` c2)
72 instance (Monoid a, Monoid b, Monoid c, Monoid d) => Monoid (a,b,c,d) where
73 mempty = (mempty, mempty, mempty, mempty)
74 (a1,b1,c1,d1) `mappend` (a2,b2,c2,d2) =
75 (a1 `mappend` a2, b1 `mappend` b2,
76 c1 `mappend` c2, d1 `mappend` d2)
78 instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) =>
79 Monoid (a,b,c,d,e) where
80 mempty = (mempty, mempty, mempty, mempty, mempty)
81 (a1,b1,c1,d1,e1) `mappend` (a2,b2,c2,d2,e2) =
82 (a1 `mappend` a2, b1 `mappend` b2, c1 `mappend` c2,
83 d1 `mappend` d2, e1 `mappend` e2)
85 -- lexicographical ordering
86 instance Monoid Ordering where