Top/RecursionTheorem

Top | Top | recent changes | Preferences

Section 6.1 of Sipser presents the recursion theorem. Roughly, this says that when building a Turing Machine, you can assume the TM knows its own encoding.

We illustrate what this means using python. Here is a python program that prints itself:

#!/usr/bin/python
M = r'''Q="'" + "''"
NL="\n"
SELF="#!/usr/bin/python" + NL + "M = r" + Q + M + Q + NL + M
print SELF
'''
Q="'" + "''"
NL="\n"
SELF="#!/usr/bin/python" + NL + "M = r" + Q + M + Q + NL + M
print SELF

If you save this program in a file 'self.py', then you can verify that it prints its own encoding:

$ python self.py > self
$ diff self.py self

Now, below is a python program that can generate programs that know their own encodings. If you run this program and pass it some python code P on stdin, it will output a program P' that starts by storing its own encoding (the text for P') in a variable SELF, and then runs P. The code fragment P is free to use the variable SELF.

For example, if you save the program below as recthm.py, then the program above could be generated by running

$ echo 'print SELF' | python recthm.py > self.py

Here is the program:

#!/usr/bin/python

# given a python program P with free variable SELF
# output a python program P' that is like P, except
# where SELF is initialized to the string P'

import sys
P = sys.stdin.read()

M = r'''
SELF_QUOTE="'" + "''"
SELF_NL="\n"
SELF="#!/usr/bin/python" + SELF_NL + "SELF_M = r" + SELF_QUOTE + SELF_M + SELF_QUOTE + SELF_NL + SELF_M + SELF_NL
''' + P

print "#!/usr/bin/python"
print "SELF_M = r'''" + M + "'''"
print M

The program is limited in the sense that the code fragment P that is passed in cannot contain the the python triple-single-quote operator " ' ' ' ".

Why is the recursion theorem useful?

Well, we can use it in ways very similar to diagonalization.

For example, suppose we want to prove that there is no python procedure HALT(P) that takes a python program P (as a string) and returns 1 if P halts when run, and 0 otherwise.

Suppose there were such a procedure.

Consider passing the folllowing code fragment to the program recthm.py above.

def HALT(P):
   ...  (def'n of HALT goes here) ...

if HALT(SELF):
   while True:
      pass

Giving this code fragment to recthm.py would generate a python program P' such that if HALT(P') returned 1, then P' would not halt, and if HALT(P') returned 0, then P' would halt. Thus, the procedure HALT(P) does not work for this program P'.

For other examples, see theorems 6.3 - 6.6 of Sipser.


Top | Top | recent changes | Preferences
This page is read-only | View other revisions
Last edited December 3, 2004 6:42 pm by Neal Young (diff)
Search: