1

I've got an internal state, which has to be updated continuously. Following functional programming, the state is immutable and the loop is implemented using recursion. An example way of how this could be implemented in a hypothetical (C based) language is then:

void RunUpdateLoop(WorldState world)
{
    WorldState newWorld = Update(world);
    RunUpdateLoop(newWorld);
}

However, this would quickly result in a stack overflow (assuming tail recursion optimization doesn't happen). How can this be implemented in a functional way without resulting in a stack overflow?

Layl Conway
  • 385
  • 9
  • 17
  • 2
    Why wouldn't you have tail call optimization in a hypothetical language, if you wanted to do functional programming in it? It's pretty much a requirement for purely functional programming since you need to have recursion (at some level) for looping. – David Young Sep 08 '14 at 02:55
  • A problem is that in for example C++, tail call optimization might be disabled in debug compile target (along with a bunch of other optimizations). – Layl Conway Sep 08 '14 at 02:59
  • Hmm, I wouldn't suggest sticking that strictly to purely functional programming in C++. This kind of thing in particular isn't a good fit for C++ (no recursion for looping makes it difficult). Don't get me wrong, I like functional programming (in fact, most of my activity on here by far is FP related), but it's better to go *with* the language that you are using rather than try to use a style that isn't well supported (not to say C++ doesn't have some support for FP, just that this specific problem is an area where it really wouldn't work well in C++). – David Young Sep 08 '14 at 03:06

1 Answers1

0

If there was a tail recursion optimization, the generated code would be very similar to something like

void RunUpdateLoop(WorldState world) {
    while(1) { world = RunUpdateLoop(world); }
}

No?

Of course you could say that's not "functional" enough, but you're asking for a "functional" solution in a procedural language. So, not quite sure what you are after.

You can always simulate a call stack in the heap with a stack-like data structure, and do the tail-recursion optimization yourself, but in this case it will once again collapse to something very similar to the above.

BadZen
  • 4,083
  • 2
  • 25
  • 48