tail recursion only makes sense in Monads that blo...
# arrow
r
tail recursion only makes sense in Monads that blow the stack like List, Option, Either, etc… Async monads are stack safe because they trampoline when they run. If you look at the IO ADT you see all those flatMap and binds are nothing but creating a data structure that unfolds into a terminal value when you run IO at the edge. This value can be calculated by async or concurrent processes that would scape the stack.
tailrec
is designed so that recursive functions don’t blow up the stack but all async monads like IO are safe because they jump out of the stack before it fills up by moving the computation into the heap via ADTs and classes that hold computations in memory.
s
For those interested in the internals. https://github.com/arrow-kt/arrow/blob/master/modules/fx/arrow-fx/src/main/kotlin/arrow/fx/internal/Utils.kt#L198 We can expose this function as
suspend trampoline(): Unit
as well.
👍 2