[project @ 2003-03-08 19:02:39 by panne]
[ghc-base.git] / Control / Monad / Fix.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Control.Monad.Fix
4 -- Copyright   :  (c) Andy Gill 2001,
5 --                (c) Oregon Graduate Institute of Science and Technology, 2002
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  experimental
10 -- Portability :  portable
11 --
12 -- The Fix monad.
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
22 module Control.Monad.Fix (
23         MonadFix(
24            mfix -- :: (a -> m a) -> m a
25          ),
26         fix     -- :: (a -> a) -> a
27   ) where
28
29 import Prelude
30 import System.IO
31
32 fix :: (a -> a) -> a
33 fix f = let x = f x in x
34
35 class (Monad m) => MonadFix m where
36         mfix :: (a -> m a) -> m a
37
38 -- Instances of MonadFix for Prelude monads
39
40 -- Maybe:
41 instance MonadFix Maybe where
42     mfix f = let a = f (unJust a) in a
43              where unJust (Just x) = x
44
45 -- List:
46 instance MonadFix [] where
47     mfix f = case fix (f . head) of
48                []    -> []
49                (x:_) -> x : mfix (tail . f)
50
51 -- IO:
52 instance MonadFix IO where
53     mfix = fixIO