Possibly Pythonic Tail Call Optimization (TCO/TRE)

Chris Angelico rosuav at gmail.com
Wed Jul 15 08:22:16 EDT 2015


On Wed, Jul 15, 2015 at 7:13 PM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Chris Angelico wrote:
>>
>> I'm still interested in the explicit "replace current stack frame with
>> this call" operation. Calling it "goto" seems wrong, as most languages
>> with goto restrict it to _within_ a function,
>
>
> This just suggests to me is that most language designers
> are not very imaginative. :-)
>
> A tail call *is* a goto. That's how you implement one in
> assembly language -- you write a jump instruction instead
> of a call instruction. The jump doesn't have to be to
> the same function.
>

Sure it is; but then, a while loop is a goto, but we don't call them
goto loops. Ultimately, assembly language lets you treat everything
the same way - in some CPUs, a jump is an assignment to the
instruction pointer register, and is thus the same kind of operation
as any other. In real-mode Intel 80x86 Assembly, there are
unconditional and conditional jumps, where conditional jumps are
limited to the shortest possible form of jump (relative jumps within
+/- 128 bytes), but other than that, there's no distinctions between
"if" statements, "while" loops, etc, etc. (Yes, there's also
near-call, far-call, and interrupt, which push the instruction
pointer, the IP plus the code segment, and the IP, CS, and the flags
register, respectively - but then still just do a straight jump to the
other location.) But in high level languages, we differentiate all of
them, because the human who reads the code should differentiate
between them. You don't use Python's "while" statement as a sort of
"if", nor vice versa. At least, not usually...

while x < 1:
    print("x is less than one!")
    break
else:
    print("x is one or greater!")

ChrisA



More information about the Python-list mailing list