Skip to content

Instantly share code, notes, and snippets.

@lynn
Forked from nandor/Turing.hs
Last active April 15, 2017 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynn/450563b2a1d77f5a6f1d80f81a1131f8 to your computer and use it in GitHub Desktop.
Save lynn/450563b2a1d77f5a6f1d80f81a1131f8 to your computer and use it in GitHub Desktop.
Haskell Turing Machine
import Data.Map(Map, fromList, lookup, union)
import Control.Monad(msum)
fromMay d = (!!0) . foldr (:) [d]
mapIns :: (Ord k) => k -> a -> Map k a -> Map k a
mapIns k a = union (fromList [(k, a)])
-- | A TM to add 1 to a binary natural.
incr :: (Int, [Int], [(Int, Int, Char, Char, Int)])
incr
= (0, [ 2 ],
[ (0, 0, '0', '0', 1)
, (0, 0, '1', '1', 1)
, (0, 1, '_', '_', (-1))
, (1, 1, '1', '0', (-1))
, (1, 2, '0', '1', 0)
, (1, 2, '_', '1', 0)
])
-- | Run a TM on a strip
run pos strip (mInit, mFinal, mTrans) = run' mInit pos strip mFinal mTrans
run' situation pos strip mFinal mTrans
| any (==situation) mFinal = Just strip
| 1>0 = msum $ [run' tFinal (pos + tDir) (mapIns pos tJot strip) mFinal mTrans
| unit <- [fromMay '_' (Data.Map.lookup pos strip)],
(tInit, tFinal, tScan, tJot, tDir) <- mTrans,
tInit == situation && tScan == unit]
-- | Try it out
strip = Data.Map.fromList
[ ( 0, '1' )
, ( 1, '0' )
, ( 2, '1' )
, ( 3, '1' )
]
try = run 0 strip incr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment