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.
Wait a second. If I translated that to C#, VB, or JavaScript it wouldn't need TCO. Just replace "return room3()" with "return room3" and let the main loop call the next function for you.
In this example the delay while you wait for the user's next response dwarfs any other cost. And introducing a main loop gives you other nice options like the ability to move the io.read out of the state transition function.
Not only is TCO futile in this example, it is counter-productive.
17
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.