Added execute instruction function

This commit is contained in:
Claudio Maggioni (maggicl) 2020-10-27 16:09:56 +01:00
parent 4076899334
commit d12b9590b7
1 changed files with 14 additions and 7 deletions

View File

@ -52,8 +52,8 @@ errorDesc :: Error -> String
errorDesc NegTape = "ERROR: '<' not working. Cannot access negative tape positions."
errorDesc LoopNoMatch = "ERROR: '[' or ']' not working. Matching parenthesis not found."
incrInt :: ProgState -> ProgState
incrInt p = p { ip = ip p + 1 }
incrIP :: ProgState -> ProgState
incrIP p = p { ip = ip p + 1 }
execAdd :: ProgState -> Either Error ProgState
execAdd p = Right p { tape = newTape }
@ -91,12 +91,19 @@ findMatching prg start wd = case wd of
| otherwise = fmHelper (upd s) acc b ob upd limit
where c = prg !! start
execLoopStart :: ProgState -> Either Error ProgState
execLoopStart w = case newInt of
execLoop :: WalkingDirection -> ProgState -> Either Error ProgState
execLoop d w = case posOrF of
Just n -> Right w { ip = n }
Nothing -> Left LoopNoMatch
where jump = (tape w !! dp w) == Byte 0
posOrF = if jump then findMatching (program w) (ip w) Forward else Just $ ip w
newInt = fmap (+1) posOrF
posOrF = if jump then findMatching (program w) (ip w) d else Just $ ip w
executeInstruction :: Instruction -> ProgState -> Either Error ProgState
executeInstruction i = (fmap incrIP) . case i of
TapeLeft -> execTapeLeft
TapeRight -> execTapeRight
Add -> execAdd
Sub -> execSub
Out -> execOut
LoopStart -> execLoop Forward
LoopEnd -> execLoop Backward