本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
34What Programs Cannot Do: The Halting Problem
Every programmer has waited in front of a program that does not answer, wondering whether it is still computing or caught in a loop for ever. A tool that read any program, with its input, and said for certain whether it would ever stop would catch a whole family of bugs before they happen. Such a tool cannot exist. Not because nobody has been clever enough yet: there is a proof, short enough for a page, that every attempt must fail on some program.
The proof rests on one idea that this book has used since the toy machine: a program is data. A program can read another program, run it, or change it, and nothing prevents a program from reading itself. The chapter starts there, proves the theorem, then measures what it leaves possible, on a machine small enough to be decided completely.
You already know
A von Neumann machine keeps the program and its data in the same memory, and assembly language names the instructions of the processor (chapter 13). The toy machine has cells of one byte, four registers, a program counter, a stack pointer and three flags, and the grade 11 project built its assembler and simulator (chapter 21). A recursive function calls itself on a smaller case (chapter 22).
34.1 A program is data
The text of a Python program is a string. Python’s own module ast turns that string into a tree of the program’s parts, which another program can walk and count.
"""A program reading a program: Python's ast module parses euclid.py."""
import ast
from pathlib import Path
source = Path("euclid.py").read_text()
tree = ast.parse(source) # the text becomes a tree
kinds = {}
for node in ast.walk(tree):
name = type(node).__name__
kinds[name] = kinds.get(name, 0) + 1
print(len(source), "characters,", len(source.splitlines()), "lines")
print("functions:", [n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)])
print("while loops:", kinds.get("While", 0), " for loops:", kinds.get("For", 0),
" calls:", kinds.get("Call", 0))
$ python read_program.py
219 characters, 10 lines
functions: ['gcd']
while loops: 1 for loops: 0 calls: 2
euclid.py of the last section, seen as data.A toy-machine program is even more plainly data: after assembly, it is numbers. The simulator reads them as instructions only when it runs them, and a single changed byte changes what the program does.
"""A toy-machine program kept in a Python string: data until the simulator runs it."""
from toymachine import Machine, assemble
COUNTDOWN = """
LOADI R0, 3
LOADI R1, 1
loop: OUT R0
SUB R0, R1
JNZ loop
HALT
"""
code = assemble(COUNTDOWN) # 256 bytes of memory
print("the first ten bytes:", code[:10])
m = Machine(code)
m.run()
print("outputs:", m.outputs, " steps:", m.steps)
code[1] = 5 # change one byte of the program
m = Machine(code)
m.run()
print("after changing byte 1 to 5:", m.outputs, " steps:", m.steps)
$ python toy_interpreter_use.py
the first ten bytes: [4, 3, 5, 1, 80, 0, 20, 1, 64, 4]
outputs: [3, 2, 1] steps: 12
after changing byte 1 to 5: [5, 4, 3, 2, 1] steps: 18
LOADI: the starting count.Definition 34.1 (Compiler)
A compiler is a program that reads a program written in one language and writes an equivalent program in another, usually the machine code of a processor, without running it. An interpreter reads a program and carries out its instructions itself, as the toy machine’s simulator does.
Programs that read programs are everywhere: the Python interpreter, compilers, the checker ruff that this book runs on every listing, and the browser that runs the scripts of a web page. Whether one of them could also tell, for every program, whether it stops, is the question of this chapter.
34.2 Decidable problems
Definition 34.2 (Decision problem, decidable problem)
A decision problem is a question with a yes-or-no answer about an input: “is this number prime?”, “does this graph have a cycle?”. It is decidable when some algorithm answers it correctly for every input, always stopping after a finite number of steps.
Primality is decidable: trying every divisor up to the square root always ends. So is a bounded version of the question of this chapter: “does this toy program halt within steps?”. Run it for at most steps, and look.
"""Halting within k steps is decidable: run at most k steps and look."""
from programs import COUNTDOWN, FOREVER, WRAP
from toymachine import Machine, assemble
def halts_within(text, k):
m = Machine(assemble(text))
while not m.halted and m.steps < k:
m.step()
return m.halted, m.steps
for name, text in [("COUNTDOWN", COUNTDOWN), ("FOREVER", FOREVER), ("WRAP", WRAP)]:
for k in (100, 1000):
halted, steps = halts_within(text, k)
verdict = f"halts after {steps} steps" if halted else "has not halted"
print(f"{name:9} within {k:4} steps: {verdict}")
"""Three toy programs without input, used by the listings of the chapter."""
COUNTDOWN = """
LOADI R0, 3
LOADI R1, 1
loop: OUT R0
SUB R0, R1
JNZ loop
HALT
"""
FOREVER = """
loop: JMP loop
"""
WRAP = """
loop: ADDI R0, 1 ; 1, 2, ..., 255, then 0 again
JNZ loop
HALT
"""
SPIN = """
loop: ADDI R0, 1 ; counts for ever, round and round
JMP loop
"""
$ python halts_within.py
COUNTDOWN within 100 steps: halts after 12 steps
COUNTDOWN within 1000 steps: halts after 12 steps
FOREVER within 100 steps: has not halted
FOREVER within 1000 steps: has not halted
WRAP within 100 steps: has not halted
WRAP within 1000 steps: halts after 513 steps
WRAP needed steps.Running and watching gives a yes when the program stops. When it has not stopped yet, it gives nothing: the program may stop at the next step, or never. The real question has no .
Definition 34.3 (Computable function)
A function from inputs to outputs is computable when some program computes it: for every input, the program stops and gives the function’s value. A decision problem is decidable exactly when its yes-or-no function is computable.
34.3 The halting problem
The halting problem asks, for a program and an input : does , run on , ever stop?
Theorem 34.4 (Undecidability of the halting problem)
No program decides the halting problem: for every program halts(program, data) that always stops and answers yes or no, there is a program and an input on which its answer is wrong.
Proof. Take any function halts that always stops with True or False. Build from it the program below, contrarian: on an input program, it asks halts whether program stops when given itself as its input, and then does the opposite.
"""The program of the proof. Given any function that claims to decide halting,
it builds a program on which that function is wrong."""
def make_contrarian(halts):
"""halts(program, data) claims to say whether program(data) ever stops."""
def contrarian(program):
if halts(program, program): # "program stops on itself"
while True: # then run for ever
pass
return "stopped" # else stop at once
return contrarian
Now run contrarian on itself, and call that run. Since halts always stops, contrarian reaches its if, and there are two cases.
- If
halts(contrarian, contrarian)isTrue, the claim is “ stops”. But then enterswhile Trueand never stops: the claim was wrong. - If it is
False, the claim is “ never stops”. But then returns at once: wrong again.
Either way halts is wrong on the program contrarian with the input contrarian. Since halts was any function, none decides halting. ∎
halts answers about , the program reads that answer and does the other thing.The argument can be tried on real candidates. Each of the three below is a function that always answers; each one is built into its own contrarian, and the contrarian is run under a watch that gives up after lines of Python.
"""Three would-be deciders, each one defeated by its own contrarian program."""
import inspect
import sys
from contrarian import make_contrarian
class OutOfTime(Exception):
pass
def run_for(f, x, budget):
"""Run f(x), but give up after budget lines of Python have been executed."""
count = 0
def tracer(frame, event, arg):
nonlocal count
if event == "line":
count += 1
if count > budget:
raise OutOfTime
return tracer
sys.settrace(tracer)
try:
return f"stops, returning {f(x)!r}"
except OutOfTime:
return f"still running after {budget} lines"
finally:
sys.settrace(None)
def always_yes(program, data):
return True
def always_no(program, data):
return False
def no_endless_loop(program, data):
"""Looks at the source: a program without 'while True' is said to stop."""
return "while True" not in inspect.getsource(program)
for decider in [always_yes, always_no, no_endless_loop]:
c = make_contrarian(decider)
claim = "stops" if decider(c, c) else "runs for ever"
print(f"{decider.__name__:15} says c(c) {claim:13}; in fact c(c)",
run_for(c, c, 100_000))
$ python try_contrarian.py
always_yes says c(c) stops ; in fact c(c) still running after 100000 lines
always_no says c(c) runs for ever; in fact c(c) stops, returning 'stopped'
no_endless_loop says c(c) runs for ever; in fact c(c) stops, returning 'stopped'
The proof is a diagonal argument. Imagine a table with one row per program and one column per input, a tick where the program stops on that input. The contrarian’s row differs from every row of the table: on the input of row , it does the opposite of what program does on that same input, on the diagonal. So its row is in no place of the table, although the table was supposed to list every program.
History — Church and Turing, 1936
In April 1936 Alonzo Church published, in the American Journal of Mathematics, “An unsolvable problem of elementary number theory”. Alan Turing’s “On computable numbers, with an application to the Entscheidungsproblem”, in the Proceedings of the London Mathematical Society (volume dated 1937), described an imaginary machine that reads and writes symbols on a tape, and showed that some questions about such machines cannot be answered by any machine. The two works reached the same limit by different routes.
34.4 What else cannot be decided, and what is too slow
The same argument, or a reduction to halting, shows that many questions about what programs do are undecidable: does this program ever print a given line? Do these two programs give the same output for every input? Is this line of the program ever reached? A general statement covers them all: any question about the behaviour of programs, what they compute rather than how their text looks, that is true for some programs and false for others, is undecidable. This book states it without proof. Checkers like ruff are useful because they answer questions about the text, or answer “maybe” when unsure.
Decidable does not mean feasible. The bounded question of section 34.2 is decided by running steps, and can be huge. A search through every subset of objects always ends, after tries: for , about , far beyond any machine. The problem of this chapter meets a decidable question whose algorithm would need more steps than that by hundreds of orders of magnitude.
34.5 One algorithm, several languages
What a program can compute does not depend on the language it is written in. Euclid’s algorithm, for instance, runs in Python, in toy assembly with only subtraction, and in SQL with a recursive query.
"""Euclid's algorithm: the greatest common divisor of a and b."""
def gcd(a, b):
while b > 0:
a, b = b, a % b # the remainder replaces the pair
return a
print(gcd(252, 198))
$ python euclid.py
18
; euclid_asm.toy -- the gcd of 252 and 198 by subtraction (no division here)
LOADI R0, 252
LOADI R1, 198
loop: CMP R0, R1
JZ done ; equal: that is the gcd
JC swap ; R0 < R1: exchange them first
SUB R0, R1 ; R0 = R0 - R1
JMP loop
swap: PUSH R0
PUSH R1
POP R0
POP R1
JMP loop
done: OUT R0
HALT
$ python -m toymachine run euclid_asm.toy --trace
step PC instruction R0 R1 R2 R3 Z N C
1 0 LOADI R0, 252 0 0 0 0 0 0 0
2 2 LOADI R1, 198 252 0 0 0 0 0 0
3 4 CMP R0, R1 252 198 0 0 0 0 0
58 6 JZ 24 18 18 0 0 1 0 0
59 24 OUT R0 18 18 0 0 1 0 0
18
60 26 HALT 18 18 0 0 1 0 0
halted after 60 steps
A recursive query starts from one row, then computes new rows from the last ones until no new row comes.
$ python sqlrun.py euclid_sql.sql
sql> WITH RECURSIVE pairs(a, b) AS (
...> SELECT 252, 198
...> UNION ALL
...> SELECT b, a % b FROM pairs WHERE b > 0
...> )
...> SELECT a, b FROM pairs;
+-----+-----+
| a | b |
+-----+-----+
| 252 | 198 |
| 198 | 54 |
| 54 | 36 |
| 36 | 18 |
| 18 | 0 |
+-----+-----+
(5 rows)
| Python | toy assembly | SQL |
|---|---|---|
while b > 0: | loop: CMP R0, R1 | WHERE b > 0 |
JZ done | (stops when no row comes) | |
a, b = b, a % b | SUB R0, R1 (or swap) | SELECT b, a % b FROM pairs |
return a | done: OUT R0 | the row where b = 0 |
| turns of the loop | subtractions, swaps | rows |
Every general-purpose language can compute what the others compute, given enough memory and time; the languages differ in convenience and speed. The halting problem is undecidable in all of them for the same reason.
34.6 Exercises
Exercise 34.1 ★
What does halts_within(WRAP, 512) return? And halts_within(WRAP, 513)?
Solution
Solution of Exercise 34.1.
(False, 512): after steps WRAP has not halted yet. (True, 513): its HALT is the th step.
Exercise 34.2 ★
How many steps does COUNTDOWN make when its first line is LOADI R0, 5? Give a formula for LOADI R0, n.
Solution
Solution of Exercise 34.2.
Two LOADI, then turns of three instructions (OUT, SUB, JNZ), then HALT: steps, so for , as the chapter’s output shows, and for .
Exercise 34.3 ★
What would read_program.py print for a file that contains only for i in range(3): print(i)?
Solution
Solution of Exercise 34.3.
With a final line break, 28 characters, 1 lines; functions: []; while loops: 0, for loops: 1, calls: 2, the calls to range and print.
Exercise 34.4 ★
Three programs and three inputs give the table “stops, loops, stops” / “stops, stops, stops” / “loops, loops, loops” (row is program ). Write the contrarian’s row and check that it differs from each row.
Solution
Solution of Exercise 34.4.
The diagonal reads stops, stops, loops; the contrarian does the opposite: loops, loops, stops. It differs from row in column , from row in column , from row in column .
Exercise 34.5 ★
Write count_functions(path), which counts the functions defined in a Python file, methods and nested functions included.
Solution
Solution of Exercise 34.5.
def count_functions(path):
tree = ast.parse(Path(path).read_text())
return sum(isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
for n in ast.walk(tree))
ast.walk visits every node, inside classes and functions too. The tests count in a file with a function, a nested function and a method.
Exercise 34.6 ★★
Explain why “does program halt on input within steps?” is decidable, although the halting problem is not.
Solution
Solution of Exercise 34.6.
The algorithm “run on for at most steps, then answer” always stops, after at most steps, and its answer is right: either halted during those steps or it did not. The halting problem has no bound: no is large enough for every program.
Exercise 34.7 ★★
A would-be decider runs program(data) and answers True when it returns. What does it answer on a program that never stops? Why does it escape the theorem only in appearance?
Solution
Solution of Exercise 34.7.
It never answers: it waits for ever with the program. So it does not always stop, and it is not a decider in the sense of the theorem, which is about functions that always answer. It decides the “yes” cases only.
Exercise 34.8 ★★
Write first_repeat(text), which runs a toy program without IN and returns the step at which a state comes back and the length of the cycle, or None if the program halts. Apply it to SPIN and FOREVER.
Solution
Solution of Exercise 34.8.
def first_repeat(text):
m, seen = Machine(assemble(text)), {}
while not m.halted:
s = state(m)
if s in seen:
return m.steps, m.steps - seen[s]
seen[s] = m.steps
m.step()
return None
The dictionary keeps the step at which each state was first met. SPIN: , a cycle of steps. FOREVER: .
Exercise 34.9 ★★
A tiny machine has cells of one byte, two registers of one byte, a program counter of bits and one flag. How many states can it be in?
Solution
Solution of Exercise 34.9.
bits, so states, about .
Exercise 34.10 ★★
The candidate short_is_stopping says that a program stops when its source has fewer than characters. The source of contrarian has . What does try_contrarian.py print for it?
Solution
Solution of Exercise 34.10.
, so the candidate says the contrarian runs for ever; the contrarian then returns at once. The line printed is
short_is_stopping says c(c) runs for ever; in fact c(c)
stops, returning 'stopped'
and the tests check it.
Exercise 34.11 ★★
Argue that “does this program ever print anything?” is undecidable: from a decider for it, build a decider for halting.
Solution
Solution of Exercise 34.11.
Suppose prints(program, data) decides whether a program ever prints. Given and , build the program : “run on with all its printing thrown away, then print done”. prints something exactly when halts on . So prints(Q, ...) would decide whether halts on , for every and , which the theorem forbids. Hence no such prints exists.
Exercise 34.12 ★★★
Write the proof of the theorem in your own words, and say exactly where it uses that halts always stops.
Solution
Solution of Exercise 34.12.
Suppose some program always answers, correctly, whether a program stops on an input. Build the contrarian, which asks it about a program run on itself and does the opposite. Ask about the contrarian run on itself: a “yes” makes it loop, a “no” makes it stop, so the answer is wrong in both cases, against the supposition. The proof uses that halts always stops in the line “the contrarian reaches its if”: if halts could run for ever, the contrarian could run for ever inside it, and a “no” would never have been given, so nothing would be wrong.
Exercise 34.13 ★★★
Prove that a machine with possible states, whose next state depends only on its current one, either halts within steps or never halts.
Solution
Solution of Exercise 34.13.
Suppose the machine runs steps without halting. It has then been in states, counting the first, among only possible ones: two of them are equal (the pigeonhole principle), say at steps . Since the next state depends only on the current one, the states from step on repeat those from step on: the run goes round the cycle from to for ever, and none of those states is a halted one, since the machine went on after each. So it never halts. Hence a machine that halts does so within steps.
Exercise 34.14 ★★★
Write a toy program that reads and with IN and prints by repeated addition. Test it from Python on several pairs, including .
Solution
Solution of Exercise 34.14.
IN R0 IN R1 LOADI R2, 0 LOADI R3, 1
CMP R1, R2 JZ done (if , the product stays )
loop: ADD R2, R0 SUB R1, R3 JNZ loop
done: OUT R2 HALT
Without the test, would first become after the subtraction, and the loop would run times. The tests compare with modulo for in , , , , and from to : the machine computes modulo .
Exercise 34.15 ★★★
Why is a running Python program not a machine with finitely many states, so that the repeat detector of the problem cannot decide its halting?
Solution
Solution of Exercise 34.15.
Python’s integers have no fixed size, and lists, strings and dictionaries can grow as long as the program likes. A program that keeps adding to an integer, or appending to a list, never returns to an earlier state: there is no finite set of states for the pigeonhole principle to work on. (A real computer’s memory is finite, but so large that the bound would be of no use, and a program that reaches its limit stops with an error rather than looping.)
34.7 Problem: A Machine That Can Be Decided
Problem 34.1
Weekend problem — deciding the toy machine
The theorem is about programs that may use as much memory as they like. The toy machine has bytes. This problem shows that for its programs without IN, halting is decidable, and measures the price.
"""For the toy machine without IN, halting is decidable: watch for a repeated state."""
from programs import COUNTDOWN, FOREVER, SPIN, WRAP
from toymachine import Machine, assemble
def state(m):
"""Everything that decides the future: memory, registers, PC, SP, flags."""
return bytes(m.mem + m.reg + [m.pc, m.sp, m.flags["Z"], m.flags["N"], m.flags["C"]])
def decide(text):
m, seen = Machine(assemble(text)), set()
while not m.halted:
s = state(m)
if s in seen: # the same state: the same future
return "never halts", m.steps, len(seen)
seen.add(s)
m.step()
return "halts", m.steps, len(seen)
for name, text in [("COUNTDOWN", COUNTDOWN), ("FOREVER", FOREVER), ("WRAP", WRAP),
("SPIN", SPIN)]:
verdict, steps, states = decide(text)
print(f"{name:9}: {verdict:11} decided after {steps:3} steps,"
f" {states:3} states stored")
$ python repeat_detector.py
COUNTDOWN: halts decided after 12 steps, 12 states stored
FOREVER : never halts decided after 1 steps, 1 states stored
WRAP : halts decided after 513 steps, 513 states stored
SPIN : never halts decided after 513 steps, 513 states stored
Part I — The state of the machine.
- List what
staterecords. Why do the outputs printed so far not belong to it? - Why must a program without
INbehave the same way each time it is in the same state? - How many bytes and bits make up a state? Count memory, registers,
PC,SPand flags. - How many different states can the machine be in?
Part II — The bound.
- Show that a run of more steps than there are states meets some state twice.
- Show that a run that meets a state twice never halts.
- Conclude: every toy program without input halts or repeats a state within how many steps?
- Write that number as a power of ten.
Part III — The detector.
- Why does
decidealways stop? - Why does it decide
FOREVERafter one step? - Explain the steps of
SPIN: what repeats, and when? WRAPandSPINboth take steps. Why do they get different verdicts?- Each stored state takes about bytes. How much memory would the detector need for a program that runs steps before repeating?
- The detector stores every state. Describe a way to detect a repeat while keeping only two machines (one stepping once, the other twice).
Part IV — Why it fails for Python.
- What does
INchange in Part I? - Why does the proof of the theorem not apply to the toy machine without input?
- Could
contrarianbe written as a toy program without input that takes another toy program as data? What stops it? - Why is the bound of question 7 useless in practice?
- Why does nothing like this bound exist for Python programs?
- State the result: what is decidable for the toy machine without input, within what bound, and why it does not contradict the theorem.
Solution
Solution of Problem 34.1.
1. The cells of memory, the four registers, PC, SP and the three flags. The outputs already printed have no effect on the next step: no instruction reads them.
2. Each step computes the next state from the current one alone; without IN, nothing from outside enters. The same state is always followed by the same next state.
3. bytes, that is bits, plus flag bits: bits.
4. : each of the bits can be or .
5. After steps the run has passed through states. If exceeds the number of states, two are equal: the pigeonhole principle.
6. From the second time on, the run repeats what followed the first time, step for step, and comes back to the same state again, for ever. No HALT lies on that cycle, since the run went on after each of its states.
7. Within steps (exercise 34.13).
8. : about .
9. Each step either halts, or meets a state already seen, or adds a new state to seen. The last can happen at most times, so the loop ends.
10. FOREVER is JMP to address : after one step, PC is again and nothing else has changed. The state after step is the starting state.
11. SPIN adds to R0 and jumps back, so R0 goes round its values in steps. The very first state, with every flag at , never comes back: when R0 wraps from to , ADDI sets Z and C. The state after step (R0 , flags , PC ) is the first to recur, after step : a cycle of steps.
12. WRAP jumps back with JNZ, so when R0 wraps to it falls through to HALT, at step . SPIN jumps back with JMP, whatever the flags.
13. bytes, about gigabytes, for a program that is short to write.
14. Run two machines from the same start, one stepping once and the other twice per round, and compare their states after each round. If the program loops, the fast one enters the cycle and gains one step per round on the slow one, so they meet; if it halts, the fast one sees HALT. Only two states are kept.
15. With IN, the next state also depends on the next number read, which is not in the state. The same state can be followed by different states, and the input may be as long as one likes: the counting of Part I no longer bounds anything.
16. The theorem is about a decider that is itself a program of the model and works on every program of it, including the contrarian built from it. The repeat detector is a Python program, with far more memory than bytes; it is not a toy program, so it cannot be fed to itself as one.
17. A contrarian must receive a program as data and run the decider on it. Without IN, a toy program receives nothing; and the decider, with its set of up to states, would never fit in bytes.
18. At steps per second, steps take about years. The detector is correct, and it would never finish on a program that uses its states well.
19. A Python program can use ever more memory, with integers and lists that grow without limit, so it has no finite number of states: no bound like exists.
20. For toy-machine programs without IN, halting is decidable: every such program halts or repeats a state within , about , steps, since a state has bytes and flag bits. The repeat detector decides it, but it is no toy program, so the theorem is not contradicted; and the bound is far beyond any machine.