3 -----------------------------------------------------------------------------
5 -- Module : Control.Monad.Fix
6 -- Copyright : (c) Andy Gill 2001,
7 -- (c) Oregon Graduate Institute of Science and Technology, 2002
8 -- License : BSD-style (see the file libraries/base/LICENSE)
9 -- Maintainer : libraries@haskell.org
10 -- Stability : experimental
11 -- Portability : portable
15 -- For a detailed discussion, see Levent Erkok's thesis,
16 -- /Value Recursion in Monadic Computations/, Oregon Graduate Institute, 2002.
18 -----------------------------------------------------------------------------
20 module Control.Monad.Fix (
22 mfix -- :: (a -> m a) -> m a
24 fix -- :: (a -> a) -> a
29 import Control.Monad.Instances ()
30 import Data.Function (fix)
32 import Hugs.Prelude (MonadFix(mfix))
34 #if defined(__GLASGOW_HASKELL__)
39 -- | Monads having fixed points with a \'knot-tying\' semantics.
40 -- Instances of 'MonadFix' should satisfy the following laws:
43 -- @'mfix' ('return' . h) = 'return' ('fix' h)@
45 -- [/left shrinking/ (or /tightening/)]
46 -- @'mfix' (\\x -> a >>= \\y -> f x y) = a >>= \\y -> 'mfix' (\\x -> f x y)@
49 -- @'mfix' ('Control.Monad.liftM' h . f) = 'Control.Monad.liftM' h ('mfix' (f . h))@,
53 -- @'mfix' (\\x -> 'mfix' (\\y -> f x y)) = 'mfix' (\\x -> f x x)@
55 -- This class is used in the translation of the recursive @do@ notation
56 -- supported by GHC and Hugs.
57 class (Monad m) => MonadFix m where
58 -- | The fixed point of a monadic computation.
59 -- @'mfix' f@ executes the action @f@ only once, with the eventual
60 -- output fed back as the input. Hence @f@ should not be strict,
61 -- for then @'mfix' f@ would diverge.
62 mfix :: (a -> m a) -> m a
63 #endif /* !__HUGS__ */
65 -- Instances of MonadFix for Prelude monads
68 instance MonadFix Maybe where
69 mfix f = let a = f (unJust a) in a
70 where unJust (Just x) = x
71 unJust Nothing = error "mfix Maybe: Nothing"
74 instance MonadFix [] where
75 mfix f = case fix (f . head) of
77 (x:_) -> x : mfix (tail . f)
80 instance MonadFix IO where
83 -- Prelude types with Monad instances in Control.Monad.Instances
85 instance MonadFix ((->) r) where
86 mfix f = \ r -> let a = f a r in a
88 instance MonadFix (Either e) where
89 mfix f = let a = f (unRight a) in a
90 where unRight (Right x) = x
91 unRight (Left _) = error "mfix Either: Left"
93 #if defined(__GLASGOW_HASKELL__)
94 instance MonadFix (ST s) where