Tail Recursion optimization for JavaScript?

后端 未结 3 1230
生来不讨喜
生来不讨喜 2021-02-03 11:45

My apologies to everyone for previous versions of this being vague. Someone has decided to have pity on the new girl and help me rewrite this question - here\'s an update that

3条回答
  •  无人共我
    2021-02-03 11:46

    One possible optimization of recursion is to evaluate lazily, that is, return a "computation" (=function) that will return a value instead of computing and returning it straight away.

    Consider a function that sums up numbers (in a rather silly way):

    function sum(n) {
        return n == 0 ? 0 : n + sum(n - 1)
    }
    

    If you call it with n = 100000 it will exceed the stack (at least, in my Chrome). To apply the said optimization, first convert it to true tail-recursive, so that the function returns just a call to itself and nothing more:

    function sum(n, acc) {
        return n == 0 ? acc : sum(n - 1, acc + n)
    }
    

    and wrap this direct self-call with a "lazy" function:

    function sum(n, acc) {
        return n == 0 ? acc : function() { return sum(n - 1, acc + n) }
    }
    

    Now, to obtain the result from this, we repeat the computation until it returns a non-function:

    f = sum(100000, 0)
    while(typeof f == "function")
        f = f()
    

    This version has no problems with n = 100000, 1000000 etc

提交回复
热议问题