summaryrefslogtreecommitdiff
path: root/testsuite/tests/determinism/determ019/A.hs
blob: 998478020495df11b138d008d11bdf59fef72c15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TupleSections #-}
module A where

import Control.Arrow (first)
import Control.Monad.Fix
import Control.Monad

-- Reduced example from rev-state package.
-- Reproduces an issue where the tuples generated when desugaring
-- mdo have nondeterministic order of components.
--
-- Consider:
--
--    do rec
--      a <- f b
--      b <- f a
--      return a
--
-- Compare:
--
--  do
--    (a, b) <- mfix $ \ ~(a, b) -> do
--      a <- f b
--      b <- f a
--      return (a, b)
--    return a
--
-- vs
--
--  do
--    (b, a) <- mfix $ \ ~(b, a) -> do
--      a <- f b
--      b <- f a
--      return (b, a)
--    return a

newtype StateT s m a = StateT
  { runStateT :: s -> m (a, s) }

instance MonadFix m => Monad (StateT s m) where
  return x = StateT $ \s -> pure (x, s)
  m >>= f = StateT $ \s -> do
    rec
      (x, s'') <- runStateT m s'
      (x', s') <- runStateT (f x) s
    return (x', s'')

instance MonadFix m => Applicative (StateT s m) where
  (<*>) = ap
  pure = return

instance Functor m => Functor (StateT s m) where
  -- this instance is hand-written
  -- so we don't have to rely on m being MonadFix
  fmap f m = StateT $ \s -> first f `fmap` runStateT m s