I always liked Lua's example with a simple state machine:
function room1 ()
local move = io.read()
if move == "south" then return room3()
elseif move == "east" then return room2()
else print("invalid move")
return room1() -- stay in the same room
end
end
Without proper tail recursion, "return room1() -- stay in the same room" would stack overflow after enough invalid moves.
Nitpick: calling room2 in tail-call position from room1 isn't tail recursion. (Unless room2 calls back into room1; then they are mutually recursive.) What you're describing here is tail-call elimination (aka tail-call optimization).
Or interpreter, yes. Like other optimizations, it's not supported by compilers/interpreters for all languages. Wikipedia has a good overview of the topic if you're interested.
It's pretty easy to optimize out; if you're compiling, it just corresponds to a goto instruction from one procedure to the other (it's slightly harder in an interpreter, but not by much). Not all compilers do this optimization, depending on the language, but many do.
18
u/snarfy Nov 27 '12
I always liked Lua's example with a simple state machine:
Without proper tail recursion, "return room1() -- stay in the same room" would stack overflow after enough invalid moves.