data Var = X | Y | Z deriving (Show, Eq) 

data Exc = E | H | K deriving (Show, Eq)


type State = [(Var, Integer)]

type EnvX  = [(Exc, Cont)]

lkp :: Var -> State -> Integer
lkp x [] = 0
lkp x ((y,z):s) = if x == y then z else lkp x s

lkpX :: Exc -> EnvX -> Cont
lkpX x [] = id
lkpX x ((y,z):s) = if x == y then z else lkpX x s


upd :: Eq a => a -> b -> [(a,b)] -> [(a,b)]
--upd x z s = (x,z):s 
upd x z [] = [(x,z)]
upd x z ((y,w):s) = if x == y then (x,z):s
                       else (y,w):upd x z s

init :: [(a,b)]
init = []


data AExp = N Integer | V Var 
          | AExp :+ AExp | AExp :- AExp | AExp :* AExp

aexp :: AExp -> State -> Integer
aexp (N z) _      = z
aexp (V x) s      = lkp x s
aexp (a0 :+ a1) s = aexp a0 s + aexp a1 s
aexp (a0 :- a1) s = aexp a0 s - aexp a1 s
aexp (a0 :* a1) s = aexp a0 s * aexp a1 s


data BExp = TT | FF | AExp :== AExp | AExp :<= AExp 
          | Not BExp | BExp :&& BExp | BExp :|| BExp

bexp :: BExp -> State -> Bool
bexp TT _ = True
bexp FF _ = False
bexp (a0 :== a1) s = aexp a0 s == aexp a1 s
bexp (a0 :<= a1) s = aexp a0 s <= aexp a1 s
bexp (Not b) s = not (bexp b s)
bexp (a0 :&& a1) s = bexp a0 s && bexp a1 s
bexp (a0 :|| a1) s = bexp a0 s || bexp a1 s


data Stmt = Skip | Stmt :\ Stmt 
          | Var := AExp
          | If BExp Stmt Stmt
          | While BExp Stmt
          | Handle Stmt Exc Stmt
          | Raise Exc
          | Twice 

type Cont = State -> State

cond :: (State -> Bool) -> Cont -> Cont -> Cont
cond p c0 c1 s = if p s then c0 s else c1 s

fix :: ((Cont -> Cont) -> Cont -> Cont) -> Cont -> Cont
fix f = f (fix f) 


stmt :: Stmt -> EnvX -> Cont -> Cont
stmt Skip envX = id
stmt (stm0 :\ stm1) envX = stmt stm0 envX . stmt stm1 envX
stmt (x := a) envX = \ c -> \ s -> c (upd x (aexp a s) s)
stmt (If b stm0 stm1) envX
          = \ c -> cond (bexp b) (stmt stm0 envX c) 
                                 (stmt stm1 envX c)
stmt (While b stm0) envX = fix f
    where f g c = cond (bexp b) (stmt stm0 envX (g c)) c
stmt (Handle stm0 exc stm1) envX =
    \ c -> stmt stm0 (upd exc (stmt stm1 envX c) envX) c
stmt (Raise exc) envX = \ _ -> lkpX exc envX
stmt Twice envX = \ c -> c . c

fac :: Stmt 
fac = (Y := N 1) :\ 
      (While (Not (N 1 :== V X))
        (((Y := (V Y :* V X)) :\Twice) :\
         (X := (V X :- N 1))
        )
      )



test0 = (X := N 17) :\ Raise E :\ (Y := N 43)

test1 = Handle (test0 :\ (Z := (V X :+ V Y))) 
                               E (X := (V X :+ N 100))
test2 = Handle test0 E (X := (V X :+ N 100))
                        :\ (Z := (V X :+ V Y))


test3 = Handle test0 E (X := (V X :+ N 100) :\ Raise E)
                        :\ (Z := (V X :+ V Y))

test4 = (X := N 17) :\ Twice :\ (Y := (V Y :+ N 1))
