How to handle "large iterations" using recursion?

Asked

Viewed 164 times

6

In the context of functional programming, it is said that any type of loop repeats (such as for or while) should be set aside in favor of recursion.

But as the number of elements of the work begins to grow, recursion can lose to the most imperative repetition loops, since they do not suffer from the problem of call stack.

Is it possible to solve this problem? How, in functional programming, to deal with the iteration of a large amount of data, in Javascript?

I’ve heard of "Tail call optimisation", but it seems to me that this feature is not yet supported, as shown in Node.Green.

Tabela de suporte a tail call optimisation no Node.green

  • 1

    This might help: https://www.sitepoint.com/recursion-functional-javascript/

  • PS: Although similar, my question is different of this. This is because my question whether there is a way around this problem, even without the optimization (not yet implemented) of the Ecmascript 2015 specification (ES6).

  • 3

    It is worth remembering that not all recursive algorithms are "tail" and the Tail call optmization shall apply only to those who are. Until there are ways to convert a recursion to use Tail calls, but if you are dealing with large amount of data that will surely burst the stack, an alternative may simply be to not use recursion :-) I rarely use it, so I don’t know if there’s any fancy solution for large data volumes...

  • 2

    I don’t know if I can answer that other than with a "don’t use recursion in languages that weren’t made for this". Tail optimization is key to accepting recursion that does not go beyond trivial. If the language supports then there is no such problem as long as the recursion is tail.

  • 2

    "Is it possible to resolve this"? Well, every solution I know for this iterates on elements of a stack, imperatively. This transforms the recursion logic of "callstack" to throw the variables into a suitable stack object

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.