'Wrapping StateT with ExceptT
I'm having trouble figuring how to wrap a StateT with an ExceptT (I'm pretty new to Haskell). I have this (incomplete, working) code:
-- Initialise the computer and run the program
runProgram pr dv = do
let comp = Computer { program = pr
, dataVals = dv
, acc = 0
, pc = 0
, halted = False
}
evalStateT execute comp
-- Main execution "loop"
execute :: StateT Computer IO ()
execute = do
output <- step
liftIO $ putStr output
comp <- get
if halted comp
then return ()
else execute
-- Execute a single step/cycle
step :: Monad m => StateT Computer m String
step = do
comp <- get
-- TODO handle out of range PC and other errors here?
let Instruction lineNo opCode operand = program comp !! pc comp
-- TODO add rest of instructions
case opCode of
HALT -> do
put $ comp{ halted = True }
return "HALT\n"
LINE -> do
let comp' = comp{ pc = pc comp + 1 }
put comp'
return "\n"
PRINT -> do
let comp' = comp{ pc = pc comp + 1 }
put comp'
let TextOperand s = operand
return s
_ -> do
let comp' = comp{ pc = pc comp + 1 }
put comp'
return $ "step: PC = " ++ (show $ pc comp') ++ "\n"
I'd like to add some error handling to step (see "TODO" comment) so I figured that wrapping the StateT in an ExceptT would allow me to do some checks which return an error status instead of continuing if something's wrong (like PC being out of range). However, I can't figure out how - I've tried lots of combinations but none work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
