[project @ 2003-04-11 11:10:57 by ross]
[ghc-base.git] / Data / Monoid.hs
diff --git a/Data/Monoid.hs b/Data/Monoid.hs
new file mode 100644 (file)
index 0000000..a328639
--- /dev/null
@@ -0,0 +1,60 @@
+-----------------------------------------------------------------------------
+-- |
+-- Module      :  Data.Monoid
+-- Copyright   :  (c) Andy Gill 2001,
+--               (c) Oregon Graduate Institute of Science and Technology, 2001
+-- License     :  BSD-style (see the file libraries/base/LICENSE)
+-- 
+-- Maintainer  :  libraries@haskell.org
+-- Stability   :  experimental
+-- Portability :  non-portable (requires extended type classes)
+--
+-- Declaration of the Monoid class, and instances for list and functions.
+--
+--       Inspired by the paper
+--       /Functional Programming with Overloading and
+--           Higher-Order Polymorphism/, 
+--         Mark P Jones (<http://www.cse.ogi.edu/~mpj/>)
+--               Advanced School of Functional Programming, 1995.
+-----------------------------------------------------------------------------
+
+module Data.Monoid (
+       Monoid(..)
+  ) where
+
+import Prelude
+
+-- ---------------------------------------------------------------------------
+-- | The monoid class.
+-- A minimal complete definition must supply 'mempty' and 'mappend',
+-- and these should satisfy the monoid laws.
+
+class Monoid a where
+       mempty  :: a
+       -- ^ Identity of 'mappend'
+       mappend :: a -> a -> a
+       -- ^ An associative operation
+       mconcat :: [a] -> a
+
+       -- ^ Fold a list using the monoid.
+       -- For most types, the default definition for 'mconcat' will be
+       -- used, but the function is included in the class definition so
+       -- that an optimized version can be provided for specific types.
+
+       mconcat = foldr mappend mempty
+
+-- Monoid instances.
+
+instance Monoid [a] where
+       mempty  = []
+       mappend = (++)
+
+instance Monoid (a -> a) where
+       mempty  = id
+       mappend = (.)
+
+instance Monoid () where
+       -- Should it be strict?
+       mempty        = ()
+       _ `mappend` _ = ()
+       mconcat _     = ()