1

I wanted to try out in Dart some algorithms and patterns from Functional Programming, but a lot of them rely heavily on recursion, which might incur in serious memory leaks without Tail Call Optimization (TCO), which isn't mandatory for when implementing a language.

Is there an official statement on this topic from the Dart team or something about it in the documentation? I could probably figure out if this is currently present in the language by using Dart's Dev Tools and Profiling, however this way I would never be able to know the Dart team's intentions with respect to the topic, hence the raison d'être of this question.

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76

1 Answers1

3

Dart does not support tail-call optimization. There are no current plans to add it.

The primary reason is that it's a feature that you need to rely on in order to use, otherwise you get hugely inefficient code that might overflow the stack, and since JavaScript currently does not support tail call optimization, the feature cannot be efficiently compiled to JavaScript.

lrn
  • 64,680
  • 7
  • 105
  • 121
  • 1
    Not sure that is an entirely true statement; any tail recursive function can be automatically translated to a simple loop. You just need a compiler that is built with TCO in mind. Not saying this is a trivial thing to do, just that it would be possible for Dart to support TCO and still compile to efficient JS. – Chechy Levas Jun 30 '22 at 05:39
  • 1
    There are *mutually tail-recursive* functions that cannot be implemented as a simple loop. My go-to-example is is a three-state state machine implementation: https://gist.github.com/lrhn/966a77b8433f44af4e2c125014f42c41 Some tail recursion can be made into a loop, but when it gets just moderately complicated, that's not a viable strategy, and you get back to needing trampolines or similar tricks. – lrn Jun 30 '22 at 09:04