e04a7f6246169b00458598f7648a4ca0cb602fc4
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 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
10 --
11 -- Monadic fixpoints.
12 --
13 -- For a detailed discussion, see Levent Erkok's thesis,
14 -- /Value Recursion in Monadic Computations/, Oregon Graduate Institute, 2002.
15 --
16 -----------------------------------------------------------------------------
18 module Control.Monad.Fix (
20 mfix -- :: (a -> m a) -> m a
21 ),
22 fix -- :: (a -> a) -> a
23 ) where
25 import Prelude
26 import System.IO
27 import Control.Monad.Instances ()
29 -- | @'fix' f@ is the least fixed point of the function @f@,
30 -- i.e. the least defined @x@ such that @f x = x@.
31 fix :: (a -> a) -> a
32 fix f = let x = f x in x
34 -- | Monads having fixed points with a \'knot-tying\' semantics.
35 -- Instances of 'MonadFix' should satisfy the following laws:
36 --
37 -- [/purity/]
38 -- @'mfix' ('return' . h) = 'return' ('fix' h)@
39 --
40 -- [/left shrinking/ (or /tightening/)]
41 -- @'mfix' (\\x -> a >>= \\y -> f x y) = a >>= \\y -> 'mfix' (\\x -> f x y)@
42 --
43 -- [/sliding/]
44 -- @'mfix' ('Control.Monad.liftM' h . f) = 'Control.Monad.liftM' h ('mfix' (f . h))@,
45 -- for strict @h@.
46 --
47 -- [/nesting/]
48 -- @'mfix' (\\x -> 'mfix' (\\y -> f x y)) = 'mfix' (\\x -> f x x)@
49 --
50 -- This class is used in the translation of the recursive @do@ notation
51 -- supported by GHC and Hugs.
52 class (Monad m) => MonadFix m where
53 -- | The fixed point of a monadic computation.
54 -- @'mfix' f@ executes the action @f@ only once, with the eventual
55 -- output fed back as the input. Hence @f@ should not be strict,
56 -- for then @'mfix' f@ would diverge.
57 mfix :: (a -> m a) -> m a
59 -- Instances of MonadFix for Prelude monads
61 -- Maybe:
62 instance MonadFix Maybe where
63 mfix f = let a = f (unJust a) in a
64 where unJust (Just x) = x
66 -- List:
67 instance MonadFix [] where
68 mfix f = case fix (f . head) of
69 [] -> []
70 (x:_) -> x : mfix (tail . f)
72 -- IO:
73 instance MonadFix IO where
74 mfix = fixIO
76 instance MonadFix ((->) r) where
77 mfix f = \ r -> let a = f a r in a