File: ST.hs

package info (click to toggle)
bali-phy 4.0~beta16%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 15,192 kB
  • sloc: cpp: 119,288; xml: 13,482; haskell: 9,722; python: 2,930; yacc: 1,329; perl: 1,169; lex: 904; sh: 343; makefile: 26
file content (31 lines) | stat: -rw-r--r-- 987 bytes parent folder | download | duplicates (2)
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
{-# LANGUAGE NoImplicitPrelude #-}

module Compiler.ST (ST, runST, fixST)
    where

import Compiler.Base -- for seq
import Data.Tuple    -- for snd
import Data.Function -- for $

import Data.Functor
import Control.Applicative
import Control.Monad

data ST s a = ST { runST :: s -> (s, a) }

instance Functor (ST s) where
    fmap f t = ST (\state1 -> let (state2,   result) = runST t state1
                              in  (state2, f result)
                  )

instance Applicative (ST s) where
    pure x    = ST (\s -> (s, x))
    t1 <*> t2 = ST (\state1 -> let (state2,f) = runST t1 state1
                                   (state3,x) = runST t2 state2
                               in (state3, f x))

instance Monad (ST s) where
    f >>= g  = ST (\state1 -> let (state2,x) = runST f state1 in x `seq` runST (g x) state2)
    unsafeInterleaveIO f = ST (\state -> (state, snd $ runST f state))

fixST f   = ST (\state1 -> let result@(state2, x) = runST (f x) state1 in result)