Guest User

Untitled

a guest
Dec 6th, 2019
203
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. runMachine
  2. :: (MonadState Machine m, MonadWriter [Int] m)
  3. => Int
  4. -> m ()
  5. runMachine input = do
  6. op <- getOp
  7. case op of
  8. (Add m1 m2) -> do
  9. arithBinOp (+) m1 m2
  10. stepPc op
  11. runMachine input
  12. (Mul m1 m2) -> do
  13. arithBinOp (*) m1 m2
  14. stepPc op
  15. runMachine input
  16. Input -> do
  17. p <- read Immediate 1
  18. write input p
  19. stepPc op
  20. runMachine input
  21. Output -> do
  22. p <- read Position 1
  23. tell [p]
  24. stepPc op
  25. runMachine input
  26. (JumpT m1 m2) -> do
  27. v <- read m1 1
  28. case v of
  29. 0 -> stepPc op
  30. _ -> do
  31. p <- read m2 2
  32. setPc p
  33. runMachine input
  34. (JumpF m1 m2) -> do
  35. v <- read m1 1
  36. case v of
  37. 0 -> do
  38. p <- read m2 2
  39. setPc p
  40. _ -> stepPc op
  41. runMachine input
  42. (LessThan m1 m2) -> do
  43. arithBinOp (\v1 v2 -> if v1 < v2 then 1 else 0) m1 m2
  44. stepPc op
  45. runMachine input
  46. (EqTo m1 m2) -> do
  47. arithBinOp (\v1 v2 -> if v1 == v2 then 1 else 0) m1 m2
  48. stepPc op
  49. runMachine input
  50. Terminate -> return ()
  51.  
  52. where
  53. arithBinOp f m1 m2 = do
  54. v1 <- read m1 1
  55. v2 <- read m2 2
  56. p3 <- read Immediate 3
  57. write (f v1 v2) p3
  58.  
  59. getOp = do
  60. (Machine state pc) <- get
  61. return . parseOp $ state ! pc
  62.  
  63. write n p = do
  64. m@Machine{..} <- get
  65. put $ m { mState = mState // [(p, n)] }
  66.  
  67. read m p = do
  68. (Machine state pc) <- get
  69. case m of
  70. Position ->
  71. return $ state ! (state ! (pc + p))
  72. Immediate ->
  73. return $ state ! (pc+p)
  74.  
  75. stepPc op = do
  76. modify (\m@Machine{..} -> m { mPc = mPc + paramCt op + 1})
  77.  
  78. setPc p =
  79. modify (\m -> m { mPc = p })
RAW Paste Data