Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
State monad using Cont
{-# LANGUAGE NoMonomorphismRestriction, Rank2Types #-}
import Control.Monad.Cont
type State s v = s -> (s, v)
set :: a -> State a ()
set x = const (x, ())
get :: State a a
get = \s -> (s, s)
bind :: State a b -> (b -> State a c) -> State a c
bind ma f = \s -> let (s', v) = ma s in f v s'
ret :: a -> State x a
ret a = \s -> (s, a)
run :: s -> State s a -> (s, a)
run s f = f s
foo = get `bind` \s -> set (s + 42) `bind` \_ -> ret "foo"
c x = cont (\fred -> x `bind` fred)
cget :: CState a a
cget = c get
cset :: a -> CState a ()
cset = c . set
type CState s v = forall a . Cont (State s a) v
bar :: CState Int Int
bar = do
x <- cget
cset (x + 42)
cget
crun x f = run x $ runCont f ret
main :: IO ()
main = do
print $ crun 1000 bar
print $ run 1000 foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment