Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Музичко М.В. Курсова робота(Теорія алгоритмів).doc
Скачиваний:
15
Добавлен:
26.11.2018
Размер:
636.93 Кб
Скачать

Висновки

Під час проходження курсу з дисципліни «Теорія алгоритмів» я вчився будувати Машину Тюрінга. Переводити систему числення з двійкового в десятковий та навпаки. Основною темую курсу було дослідження роботи МТ та вцілому. Принцип роботи, знаходження комірок лічильника МТ, опис МТ. Найбільш зацікавило мене те, що при виконанні практичних робіт з дисципліни «Теорія алгоритмів» можна регулувати головку лічильника машини Тюрінга, яка виконує пошук символа на стрічці. Якщо вірно знаходить потрібний символ то машина робить перехід до наступної комірки. І таким чином вона повторюється (виконується) до тих пір поки не вийде на $-стоп.

Як практично так і теоретично під час проходження курсу я намагався засвоїти ті елементи МТ, які допоможуть мені виконати перехід вад одної системи числення до іншої. Алгоритм дії МТ діє поетапно, тобто принцип роботи полягає у послідовності введення в МТ даних для пошуку символів. МТ можна порівняти з сейфом,тобто якщо крутити кодову ручку сейфа то можна почути «хлопки» що означають, що дана комбінація «вірна» або співпала цифра і така дія триває до тих пір поки останній замок запобіжника не розімкне коло яке блукує замок;Ось по суті МТ і працює маже по такому принципу.

Список використаних джерел

  1. Енциклопедія кібернетики, т. 2, с. 444—446.

  2. Good Math, Basics: The Turing Machine (with an interpreter!), 9 лютого 2007.

  3. Henk Barendregt 1997.

  4. Kluge 2005, сторінка 51.

  5. Raúl Rojas, A Tutorial Introduction to the Lambda Calculus(англ.) -(PDF)

  6. Wolfengagen, V.E. Combinatory logic in programming. Computations with objects through examples and exercises. -- 2-nd ed. -- M.: "Center JurInfoR" Ltd., 2003. -- x+337 с. ISBN 5-89158-101-9.

  7. Навчальний проект з курсу "Основи програмування": Машина Тюрінга.

  8. Рощин А.Г., статевої Р.М. Теорія автоматів. Частина I. Тексти лекцій - Москва: МГТУ ГА, 2001. - 76 с.

  9. Фалевіч Б.Я. Теорія алгоритмів. - М.: ИНФРА-М, 2006. - С.324.

  10. Фаліна М.М. Машина Тьюрінга / / Інформатика. - № 26. - 2005. - С.12-15

  11. Теорія алгоритмів Методичний посібник з дисципліни "Математична логіка і теорія алгоритмів» / В.П. Бітюцький, Н.В. Папуловская. Єкатеринбург: ГОУ ВПО УГТУ-УПІ, 2006, с.

ДОДАТОК

У додатку буде представлено Англомовну версію машини Тюрінга. Де буде поетапно описано усі кроки виконання дії машини Тюрінга.

Basics: The Turing Machine (with an interpreter!)

Category: Basics • Haskell • Programming • programming

Posted on: February 3, 2007 6:38 PM, by Mark C. Chu-Carroll

As long as I'm doing all of these basics posts, I thought it would be worth explaining just what a Turing machine is. I frequently talk about things being Turing equivalent, and about effective computing systems, and similar things, which all assume you have some clue of what a Turing machine is. And as a bonus, I'm also going to give you a nifty little piece of Haskell source code that's a very basic Turing machine interpreter. (It's for a future entry in the Haskell posts, and it's not entirely finished, but it does work!)

The Turing machine is a very simple kind of theoretical computing device. In fact, it's almost downright trivial. But according to everything that we know and understand about computation, this trivial device is capable of any computation that can be performed by any other computing device.

The basic idea of the Turing machine is very simple. It's a machine that runs on top of a tape, which is made up of a long series of little cells, each of which has a single character written on it. The machine is a read/write head that moves over the tape, and which can store a little bit of information. Each step, the machine looks at the symbol on the cell under the tape head, and based on what it sees there, and whatever little bit of information it has stored, it decides what to do. The things that it can do are change the information it has store, write a new symbol onto the current tape cell, and move one cell left or right.

That's really it. People who like to make computing sound impressive often have very complicated explanations of it - but really, that's all there is to it. The point of it was to be simple - and simple it certainly is. And yet, it can do anything that's computable.

To really understand how that trivial machine can do computations, it helps to be a bit formal. In formal terms, we talk about a turing machine as a tuple: (S, s0, A, T), where:

S is a finite list of possible states that the machine can be in. The state is the information that the machine can store in the head to make decisions. It's a very limited amount of information; you can think of it as either a specific list of states, or a small set of small numbers. For most Turing machines, we'll use it as a specific list of states. (You'll see what I mean in a minute.)

s0 ∈ S is the initial state - the state that the machine will be in when it starts a computation.

A is the machine's alphabet, which is the set of symbols which can appear on the machine's tape.

T is the machines transition function. This is the real heart of the machine, where the computation is defined. It's a function from the machine state and the alphabet character on the current tape cell to the action that the machine should take. The action is a triple consisting of a new value for the machine's state, a character to write onto the current tape cell, and a direction to move the tape head - either left or right.

So, for example, let's look at a simple machine. This is one of the classic examples: a Turing machine that does subtraction using unary numbers. A unary number "N" is written as a series of N 1s. For the program, we'll give the machine an input in the format "N-M=" written onto the tape; after running the machine, the tape will contain the value of M subtracted from N. So, for example, we could use "1111-11=" as an input; the output would be "11".

The alphabet is the characters "1", " " (blank space), "-" (minus sign), and "=" (equal sign). The machine has four states: {"scanright", "eraseone", "subone", "skip"}. It starts in the state "scanright". It's transition function is given by the following table:FromState Symbol ToState WriteChar Dir

scanright space scanright space right

scanright 1 scanright 1 right

scanright minus scanright minus right

scanright equal eraseone space left

eraseone 1 subone equal left

eraseone minus HALT space n/a

subone 1 subone 1 left

subone minus skip minus left

skip space skip space left

skip 1 scanright space right

What this machine does is move to the right until it sees the equal sign; it erases the equal sign and moves to the left, erases one digit off of the second number, and replaces it with the equal sign (so the second number is reduced by one, and the equal sign is moved over one position). Then it scans back to the minus sign (which separates the two numbers), and erases one digit of the first number, and then switches back to scanning to the right for the equal. So one at a time, it erases one digit from each of the two numbers. When it reaches the equal sign, and starts going back to erase a digit from the second number, and hits the "-" before it finds a digit, that means its done, so it stops. Let's look at a simple execution trace. In the trace, I'll write the machine state, followed by a colon, followed by the tape contents surrounded by "[]", with the current tape cell surrounded by "{}".

scanright: [ {1}1111111-111= ]"

scanright: [ 1{1}111111-111= ]"

scanright: [ 11{1}11111-111= ]"

scanright: [ 111{1}1111-111= ]"

scanright: [ 1111{1}111-111= ]"

scanright: [ 11111{1}11-111= ]"

scanright: [ 111111{1}1-111= ]"

scanright: [ 1111111{1}-111= ]"

scanright: [ 11111111{-}111= ]"

scanright: [ 11111111-{1}11= ]"

scanright: [ 11111111-1{1}1= ]"

scanright: [ 11111111-11{1}= ]"

scanright: [ 11111111-111{=} ]"

eraseone : [ 11111111-11{1} ]"

subone : [ 11111111-1{1}= ]"

subone : [ 11111111-{1}1= ]"

subone : [ 11111111{-}11= ]"

skip : [ 1111111{1}-11= ]"

scanright: [ 1111111 {-}11= ]"

scanright: [ 1111111 -{1}1= ]"

scanright: [ 1111111 -1{1}= ]"

scanright: [ 1111111 -11{=} ]"

eraseone : [ 1111111 -1{1} ]"

subone : [ 1111111 -{1}= ]"

subone : [ 1111111 {-}1= ]"

skip : [ 1111111{ }-1= ]"

skip : [ 111111{1} -1= ]"

scanright: [ 111111 { }-1= ]"

scanright: [ 111111 {-}1= ]"

scanright: [ 111111 -{1}= ]"

scanright: [ 111111 -1{=} ]"

eraseone : [ 111111 -{1} ]"

subone : [ 111111 {-}= ]"

skip : [ 111111 { }-= ]"

skip : [ 111111{ } -= ]"

skip : [ 11111{1} -= ]"

scanright: [ 11111 { } -= ]"

scanright: [ 11111 { }-= ]"

scanright: [ 11111 {-}= ]"

scanright: [ 11111 -{=} ]"

eraseone : [ 11111 {-} ]"

Halt: [ 11111 { }- ]"

See, it works!

One really important thing to understand here is that we do not have a program. What we just did was define a Turing machine that does subtraction. The machine does not take any instructions: the states and the transition function are an intrinsic part of the machine. So the only thing this machine can do is to subtract.

The real genius of Turing wasn't just defining this simple computing machine. It was realizing the concept of the program: you could design a Turing machine whose input tape contained a description of a Turing machine - that is a program - followed by an input to the program. This single machine - the Universal Turing machine - could simulate any other Turing machine; one machine which could perform any computation.

Turing machines are a lot of fun to play with. Figuring out how to do things can be fascinating. Figuring out how to define a Universal turing machine's transition function is an amazing thing to do; it's astonishing how simple the universal machine can be!

For your enjoyment, I've implemented a Turing machine programming language. You feed it a Turing machine description, and an input string, and it will give you a trace of the machines execution like the one above. Here's the specification of the subtraction machine written in my little Turing language:

states { "scanright" "eraseone" "subtractOneFromResult" "skipblanks" } initial "scanright"

alphabet { '1' ' ' '=' '-' } blank ' '

trans from "scanright" to "scanright" on (' ') write ' ' move right

trans from "scanright" to "scanright" on ('1') write '1' move right

trans from "scanright" to "scanright" on ('-') write '-' move right

trans from "scanright" to "eraseone" on ('=') write ' ' move left

trans from "eraseone" to "subtractOneFromResult" on ('1') write '=' move left

trans from "eraseone" to "Halt" on ('-') write ' ' move left

trans from "subtractOneFromResult" to "subtractOneFromResult" on ('1') write '1' move left

trans from "subtractOneFromResult" to "skipblanks" on ('-') write '-' move left

trans from "skipblanks" to "skipblanks" on (' ') write ' ' move left

trans from "skipblanks" to "scanright" on ('1') write ' ' move right

I think it's pretty clear as a syntax, but it still needs explanation.

The first line declares the possible states of the machine, and what state it starts in. This machine has four possible states - "scanright", "eraseone", "subtractOneFromResult", and "skipblanks". When the machine starts, it will be in the state "skipright".

The second line declares the set of symbols that can appear on the tape, including what symbol will initially appear on any tape cell whose value wasn't specified by the input. For this machine the symbols are the digit 1, a blank space, the equal sign, and the subtraction symbol; the blank symbol is on any tape cell whose initial value wasn't specified.

After that is a series of transition declarations. Each declaration specifies what the machine will do for a given pair of initial state and tape symbol. So, for example, if the machine is in state "scanright", and the current tape cell contains the equal-to sign, then the machine will change to state "eraseone", write a blank onto the tape cell (erasing the "=" sign), and move the tape cell one position to the left.

Finally, the code. You'll need GHCI to run it; at the moment, it won't work in Hugs (I don't have the parsing library in my version of Hugs), and I haven't worked out the linkage stuff to make it work under the GHC compiled mode.

--

-- A Simple Turing machine interpreter

-- Copyright 2007 by Mark C. Chu-Carroll

-- markcc@gmail.com

-- http://scienceblogs.com/goodmath

--

-- You can do anything you want with this code so long as you

-- leave this copyright notice intact.

--

module Turing where

import Text.ParserCombinators.Parsec

import qualified Text.ParserCombinators.Parsec.Token as P

import Text.ParserCombinators.Parsec.Language

import System.Environment

data Motion = MoveLeft | MoveRight deriving (Show)

data Transition = Transition String String [Char] Motion Char deriving (Show)

-- from to on move write

data TuringMachine = Machine [String] String [Char] Char [Transition] deriving (Show)

-- states initial alphabet blank transitions

data MachineState = TMState [Char] Char [Char] String deriving (Show)

-- tape-left curcell curstate

getBlankSym :: TuringMachine -> Char

getBlankSym (Machine _ _ _ bl _) = bl

findMatchingTransition :: [Transition] -> String -> Char -> Maybe Transition

findMatchingTransition [] _ _ = Nothing

findMatchingTransition translist state c =

let matches = filter (transitionMatches state c) translist

in case matches of

[] -> Nothing

t:[] -> Just t

_ -> error "Ambiguous transition"

where transitionMatches state c (Transition from to on move write) =

(from == state) && (elem c on)

runTransition :: TuringMachine -> [Char] -> Char -> [Char] -> String -> Transition -> MachineState

runTransition m (l:left) c right state (Transition from tostate on MoveLeft write) =

TMState left l (write:right) tostate

runTransition m left c [] state (Transition from tostate on MoveRight write) =

TMState (write:left) (getBlankSym m) [] tostate

runTransition m left c (r:right) state (Transition from tostate on MoveRight write) =

TMState (write:left) r right tostate

stepMachine :: TuringMachine -> MachineState -> MachineState

stepMachine machine@(Machine _ _ _ _ translist) st@(TMState tapeleft c taperight state) =

let trans = findMatchingTransition translist state c

in case trans of

(Just t) -> runTransition machine tapeleft c taperight state t

Nothing -> error "No applicable transition from state"

getMachineStateString (TMState left c right state) =

(state ++ ":[" ++ (reverse left) ++ "{" ++ [c] ++ "}" ++ right ++ "]")

runTracedMachine :: TuringMachine -> [Char] -> [String]

runTracedMachine tm@(Machine states initial alphabet blank transitions) (t:tape) =

runTracedMachineSteps tm (TMState [] t tape initial) where

runTracedMachineSteps machine state =

let newstate@(TMState left c right st) = stepMachine machine state

in if st == "Halt"

then [getMachineStateString newstate]

else let trace=runTracedMachineSteps machine newstate

in ((getMachineStateString newstate):trace)

runMachine :: TuringMachine -> [Char] -> [Char]

runMachine tm@(Machine states initial alphabet blank transitions) (t:tape) =

runMachineSteps tm (TMState [] t tape initial) where

runMachineSteps machine state =

let newstate@(TMState left c right st) = stepMachine machine state

in if st == "Halt"

then (concat [(reverse left), [c], right])

else runMachineSteps machine newstate

---------------------------------------------------------------------------

-- Parsing code - implemented using the Parsec monadic parser library.

---------------------------------------------------------------------------

-- Basic setup stuff - use a standard haskell style lexer; set up the reserved words

-- and symbols in the lexer.

lexer :: P.TokenParser ()

lexer = P.makeTokenParser (haskellDef

{ P.reservedNames = ["states","alphabet","trans","from","to","on","write","move","left","right","initial","blank"] })

reserved = P.reserved lexer

symbol = P.symbol lexer

braces = P.braces lexer

parens = P.parens lexer

charlit = P.charLiteral lexer

strlit = P.stringLiteral lexer

ident = P.identifier lexer

whitespace = P.whiteSpace lexer

states = reserved "states"

alphabet = reserved "alphabet"

trans = reserved "trans"

from = reserved "from"

to = reserved "to"

on = reserved "on"

write = reserved "write"

move = reserved "move"

initial = reserved "initial"

blank = reserved "blank"

left = do { reserved "left"

; return MoveLeft

}

right = do { reserved "right"

; return MoveRight

}

-- statesDecl ::= "states" "{" strlit+ "}" "initial" strlit

statesDecl = do { states

; strlst <- braces (many1 strlit)

; initial

; i <- strlit

; return (i,strlst)

}

-- alphaDecl ::= "alphabet" "{" charlit+ "}" "blank" charlit

alphaDecl = do { alphabet

; charlst <- braces (many1 charlit)

; blank

; bl <- charlit

; return (bl, charlst)

}

-- transDecl ::= "trans" "from" strlit "to" strlit "on" "(" charlit+ ")" "write" charlit "move" ("left" | "right")

transDecl = do { trans

; from

; fromState <- strlit

; to

; targetState <- strlit

; on

; chrs <- parens (many1 charlit)

; write

; wrchar <- charlit

; move

; dir <- ( left <|> right)

; return (Transition fromState targetState chrs dir wrchar)

}

-- machine ::= statesDecl alphaDecl transDecl+

machine = do { (i,sts) <- statesDecl

; (bl,alpha) <- alphaDecl

; trans <- many1 transDecl

; return (Machine sts i alpha bl trans)

}

run :: (Show a) => Parser a -> String -> IO a

run p input

= case (parse p "" input) of

Left err -> do{ putStr "parse error at "

; print err

; error "Parse error"

}

Right x -> return x

runTParser :: String -> IO TuringMachine

runTParser input =

run (do { whitespace

; x <- machine

; eof

; return x }) input

--------------------------------------------------------------------------

-- A sample Turing program - first in the comment, and then coded into

-- a string literal, to make it easy to run tests. This sample program

-- is a basic Turing subtract - it takes a unary equation "111111-111=",

-- and leaves the result of subtracting the second from the first.

--

-- states { "one" "two" "three" "four" } initial "one"

-- alphabet { '1' ' ' '=' '-' } blank ' '

-- trans from "one" to "one" on (' ') write ' ' move right

-- trans from "one" to "one" on ('1') write '1' move right

-- trans from "one" to "one" on ('-') write '-' move right

-- trans from "one" to "two" on ('=') write ' ' move left

-- trans from "two" to "three" on ('1') write '=' move left

-- trans from "two" to "Halt" on ('-') write '-' move left

-- trans from "three" to "three" on ('1') write '1' move left

-- trans from "three" to "four" on ('-') write '-' move left

-- trans from "four" to "four" on (' ') write ' ' move left

-- trans from "four" to "one" on ('1') write ' ' move right

sampleMachine = concat ["states { \"one\" \"two\" \"three\" \"four\" } initial \"one\"\n ",

" alphabet { '1' ' ' '=' '-' } blank ' '\n ",

"trans from \"one\" to \"one\" on (' ') write ' ' move right\n ",

"trans from \"one\" to \"one\" on ('1') write '1' move right\n ",

"trans from \"one\" to \"one\" on ('-') write '-' move right\n ",

"trans from \"one\" to \"two\" on ('=') write ' ' move left\n ",

"trans from \"two\" to \"three\" on ('1') write '=' move left\n ",

"trans from \"two\" to \"Halt\" on ('-') write '-' move left\n ",

"trans from \"three\" to \"three\" on ('1') write '1' move left\n ",

"trans from \"three\" to \"four\" on ('-') write '-' move left\n ",

"trans from \"four\" to \"four\" on (' ') write ' ' move left\n ",

"trans from \"four\" to \"one\" on ('1') write ' ' move right" ]

runTracedMachineOnString :: String -> String -> IO ([String])

runTracedMachineOnString m str =

do

tm <- runTParser m

return (runTracedMachine tm str)

runMachineOnString :: String -> String -> IO String

runMachineOnString m str =

do

tm <- runTParser m

return (runMachine tm str)

sampleInput = " 11111111-111= "

------------------------------------------------------------------------

-- Main program execution scaffolding

-- main still needs a bit of work so that ghci will link correctly;

-- runs fine in GHCI, but linkage errors in GHC. For now, just load

-- this file, and then execute "runFromFile" from the command line.

------------------------------------------------------------------------

main =

do

[file] <- getArgs

m <- parseFromFile (do { whitespace

; x <- machine

; eof

; return x }) file

case m of

Right machine -> do

print "Enter input for parser:"

s <- getLine

result <- return (runMachine machine s)

print (concat ["Result:[", result, "]"])

Left x -> do

print (concat ["Parse error"])

runFromFile :: String -> IO ()

runFromFile filename =

do

m <- parseFromFile (do { whitespace

; x <- machine

; eof

; return x }) filename

case m of

Right machine -> do

print "Enter input for parser:"

s <- getLine

result <- return (runMachine machine s)

print (concat ["Result:[", result, "]"])

Left x -> do

print (concat ["Parse error"])

42