1 -----------------------------------------------------------------------------
2 -- |
4 -- Copyright : (c) Andy Gill 2001,
5 -- (c) Oregon Graduate Institute of Science and Technology, 2002
8 -- Stability : experimental
9 -- Portability : portable
10 --
12 --
13 -- For a detailed discussion, see Levent Erkok's thesis,
15 --
16 -----------------------------------------------------------------------------
20 mfix -- :: (a -> m a) -> m a
21 ),
22 fix -- :: (a -> a) -> a
23 ) where
25 import Prelude
26 import System.IO
28 import Data.Function (fix)
30 -- | Monads having fixed points with a \'knot-tying\' semantics.
31 -- Instances of 'MonadFix' should satisfy the following laws:
32 --
33 -- [/purity/]
34 -- @'mfix' ('return' . h) = 'return' ('fix' h)@
35 --
36 -- [/left shrinking/ (or /tightening/)]
37 -- @'mfix' (\\x -> a >>= \\y -> f x y) = a >>= \\y -> 'mfix' (\\x -> f x y)@
38 --
39 -- [/sliding/]
40 -- @'mfix' ('Control.Monad.liftM' h . f) = 'Control.Monad.liftM' h ('mfix' (f . h))@,
41 -- for strict @h@.
42 --
43 -- [/nesting/]
44 -- @'mfix' (\\x -> 'mfix' (\\y -> f x y)) = 'mfix' (\\x -> f x x)@
45 --
46 -- This class is used in the translation of the recursive @do@ notation
47 -- supported by GHC and Hugs.
49 -- | The fixed point of a monadic computation.
50 -- @'mfix' f@ executes the action @f@ only once, with the eventual
51 -- output fed back as the input. Hence @f@ should not be strict,
52 -- for then @'mfix' f@ would diverge.
53 mfix :: (a -> m a) -> m a
57 -- Maybe:
59 mfix f = let a = f (unJust a) in a
60 where unJust (Just x) = x
62 -- List:
64 mfix f = case fix (f . head) of
65 [] -> []
66 (x:_) -> x : mfix (tail . f)
68 -- IO: