-
-
Save lynn/450563b2a1d77f5a6f1d80f81a1131f8 to your computer and use it in GitHub Desktop.
Haskell Turing Machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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