Providing halting problem proof in commented code
# Suppose we have a function halts(program, input)
# that correctly returns True if 'program' halts on 'input',
# and False if it runs forever.
def paradox(program):
# Use the halts function to determine behavior based on
# whether 'program' halts when given itself as input.
if halts(program, program):
# If 'program' halts on itself, enter an infinite loop here.
while True:
pass # Loop forever.
else:
# If 'program' does not halt on itself, halt immediately.
return
# Now consider calling paradox with itself as input:
# paradox(paradox)
#
# If halts(paradox, paradox) returns True (predicts it halts),
# then paradox(paradox) runs the infinite loop, so it doesn't halt,
# contradicting halts's prediction.
#
# If halts(paradox, paradox) returns False (predicts it loops forever),
# then paradox(paradox) returns immediately (halts),
# again contradicting halts's prediction.
#
# This contradiction shows no such halts function can exist
# that correctly decides halting for all programs.
```</think>
```python
# This is a sketch of the classic halting problem proof embedded in code comments.
# Imagine, for the sake of contradiction, that we have a magical function `halts`
# that can decide for any program `P` and any input `x` whether `P(x)` will ever halt.
# It returns True if `P(x)` halts, False if `P(x)` runs forever.
def halts(program_source: str, input_source: str) -> bool:
# ... impossible to implement correctly for all programs ...
pass
# Using this hypothetical `halts`, we define a new function that "diagonalizes"
# against it: given a program as input, it does the opposite of what `halts`
# predicts that program would do when run on itself.
def paradox(program_source: str):
# Ask the decider what happens when `program_source` is run on itself.
if halts(program_source, program_source):
# If it says "halts", then we loop forever instead.
while True:
pass
else:
# If it says "loops forever", then we halt immediately.
return
# Now consider what happens if we feed `paradox` to itself.
# Let P = source code of `paradox`.
# Evaluate paradox(P):
# - If halts(P, P) returns True ("P(P) halts"), paradox will enter an infinite loop.
# That means P(P) does NOT halt, contradicting halts' answer.
# - If halts(P, P) returns False ("P(P) loops"), paradox will return immediately.
# That means P(P) DOES halt, again contradicting halts' answer.
#
# In both cases, assuming the existence of a correct `halts` leads to a contradiction.
# Therefore no such total halting-decider function can exist for all programs.