-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTMSimulate.hs
More file actions
64 lines (55 loc) · 2.46 KB
/
TMSimulate.hs
File metadata and controls
64 lines (55 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
{-|
Module : TMSimulate
Description : Simulates running a Turing Machine
Maintainer : Jade Kessinger
-}
module TMSimulate where
import TMAST
import Data.Map (Map)
import qualified Data.Map as Map
simulate :: Machine -> Config
simulate Machine {config = Config tape "Halt", states = _} =
Config tape "Halt"
simulate machine = simulate (doStep machine)
doStep :: Machine -> Machine
doStep Machine {config =
Config Tape {left = left, right = right, tapeHead = tapeHead} curState,
states = states
} =
case Map.lookup curState states of
Just transitions ->
case Map.lookup tapeHead transitions of
Just Transition {write = write, move = move, goto = goto} ->
let newLeftTape = stepLeftTape left move write
newRightTape = stepRightTape right move write
newHead = stepHead left right move in
Machine {config =
Config Tape {left = newLeftTape, right = newRightTape, tapeHead = newHead} goto,
states = states}
Nothing -> error ("No transition defined for " ++ tapeHead)
Nothing -> error ("No defined transitions for " ++ curState)
-- Moves the left tape one step to the left or right given a new write symbol
-- Imitates an infinite tape by modeling empty lists as blank symbols
-- Returns thet updated left tape
stepLeftTape :: [Symbol] -> Direction -> Symbol -> [Symbol]
stepLeftTape [] Lt _ = ["_"]
stepLeftTape [] Rt write = [write]
stepLeftTape leftTape Lt _ = tail leftTape
stepLeftTape leftTape Rt write = write:leftTape
-- Moves the right tape to the left or right given a new write symbol
-- Imitates an infinite tape by modeling empty lists as blank symbols
-- Returns thet updated right tape
stepRightTape :: [Symbol] -> Direction -> Symbol -> [Symbol]
stepRightTape [] Lt write = [write]
stepRightTape [] Rt _ = ["_"]
stepRightTape rightTape Lt write = write:rightTape
stepRightTape rightTape Rt _ = tail rightTape
-- Moves the head of the tape to the left or right
-- Imitates an infinite tape by modeling empty lists as blank symbols
-- Returns thet updated head
stepHead :: [Symbol] -> [Symbol] -> Direction -> Symbol
stepHead [] [] _ = "_"
stepHead [] _ Lt = "_"
stepHead _ [] Rt = "_"
stepHead leftTape _ Lt = head leftTape
stepHead _ rightTape Rt = head rightTape