What is tail call optimization?

前端 未结 10 1243
一整个雨季
一整个雨季 2020-11-21 06:36

Very simply, what is tail-call optimization?

More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of wh

相关标签:
10条回答
  • 2020-11-21 07:06

    In a functional language, tail call optimization is as if a function call could return a partially evaluated expression as the result, which would then be evaluated by the caller.

    f x = g x
    

    f 6 reduces to g 6. So if the implementation could return g 6 as the result, and then call that expression it would save a stack frame.

    Also

    f x = if c x then g x else h x.
    

    Reduces to f 6 to either g 6 or h 6. So if the implementation evaluates c 6 and finds it is true then it can reduce,

    if true then g x else h x ---> g x
    
    f x ---> h x
    

    A simple non tail call optimization interpreter might look like this,

    class simple_expresion
    {
        ...
    public:
        virtual ximple_value *DoEvaluate() const = 0;
    };
    
    class simple_value
    {
        ...
    };
    
    class simple_function : public simple_expresion
    {
        ...
    private:
        simple_expresion *m_Function;
        simple_expresion *m_Parameter;
    
    public:
        virtual simple_value *DoEvaluate() const
        {
            vector<simple_expresion *> parameterList;
            parameterList->push_back(m_Parameter);
            return m_Function->Call(parameterList);
        }
    };
    
    class simple_if : public simple_function
    {
    private:
        simple_expresion *m_Condition;
        simple_expresion *m_Positive;
        simple_expresion *m_Negative;
    
    public:
        simple_value *DoEvaluate() const
        {
            if (m_Condition.DoEvaluate()->IsTrue())
            {
                return m_Positive.DoEvaluate();
            }
            else
            {
                return m_Negative.DoEvaluate();
            }
        }
    }
    

    A tail call optimization interpreter might look like this,

    class tco_expresion
    {
        ...
    public:
        virtual tco_expresion *DoEvaluate() const = 0;
        virtual bool IsValue()
        {
            return false;
        }
    };
    
    class tco_value
    {
        ...
    public:
        virtual bool IsValue()
        {
            return true;
        }
    };
    
    class tco_function : public tco_expresion
    {
        ...
    private:
        tco_expresion *m_Function;
        tco_expresion *m_Parameter;
    
    public:
        virtual tco_expression *DoEvaluate() const
        {
            vector< tco_expression *> parameterList;
            tco_expression *function = const_cast<SNI_Function *>(this);
            while (!function->IsValue())
            {
                function = function->DoCall(parameterList);
            }
            return function;
        }
    
        tco_expresion *DoCall(vector<tco_expresion *> &p_ParameterList)
        {
            p_ParameterList.push_back(m_Parameter);
            return m_Function;
        }
    };
    
    class tco_if : public tco_function
    {
    private:
        tco_expresion *m_Condition;
        tco_expresion *m_Positive;
        tco_expresion *m_Negative;
    
        tco_expresion *DoEvaluate() const
        {
            if (m_Condition.DoEvaluate()->IsTrue())
            {
                return m_Positive;
            }
            else
            {
                return m_Negative;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:11

    Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.

    Scheme is one of the few programming languages that guarantee in the spec that any implementation must provide this optimization (JavaScript does also, starting with ES6), so here are two examples of the factorial function in Scheme:

    (define (fact x)
      (if (= x 0) 1
          (* x (fact (- x 1)))))
    
    (define (fact x)
      (define (fact-tail x accum)
        (if (= x 0) accum
            (fact-tail (- x 1) (* x accum))))
      (fact-tail x 1))
    

    The first function is not tail recursive because when the recursive call is made, the function needs to keep track of the multiplication it needs to do with the result after the call returns. As such, the stack looks as follows:

    (fact 3)
    (* 3 (fact 2))
    (* 3 (* 2 (fact 1)))
    (* 3 (* 2 (* 1 (fact 0))))
    (* 3 (* 2 (* 1 1)))
    (* 3 (* 2 1))
    (* 3 2)
    6
    

    In contrast, the stack trace for the tail recursive factorial looks as follows:

    (fact 3)
    (fact-tail 3 1)
    (fact-tail 2 3)
    (fact-tail 1 6)
    (fact-tail 0 6)
    6
    

    As you can see, we only need to keep track of the same amount of data for every call to fact-tail because we are simply returning the value we get right through to the top. This means that even if I were to call (fact 1000000), I need only the same amount of space as (fact 3). This is not the case with the non-tail-recursive fact, and as such large values may cause a stack overflow.

    0 讨论(0)
  • 2020-11-21 07:15

    Note first of all that not all languages support it.

    TCO applys to a special case of recursion. The gist of it is, if the last thing you do in a function is call itself (e.g. it is calling itself from the "tail" position), this can be optimized by the compiler to act like iteration instead of standard recursion.

    You see, normally during recursion, the runtime needs to keep track of all the recursive calls, so that when one returns it can resume at the previous call and so on. (Try manually writing out the result of a recursive call to get a visual idea of how this works.) Keeping track of all the calls takes up space, which gets significant when the function calls itself a lot. But with TCO, it can just say "go back to the beginning, only this time change the parameter values to these new ones." It can do that because nothing after the recursive call refers to those values.

    0 讨论(0)
  • 2020-11-21 07:16

    The recursive function approach has a problem. It builds up a call stack of size O(n), which makes our total memory cost O(n). This makes it vulnerable to a stack overflow error, where the call stack gets too big and runs out of space.

    Tail call optimization (TCO) scheme. Where it can optimize recursive functions to avoid building up a tall call stack and hence saves the memory cost.

    There are many languages who are doing TCO like (JavaScript, Ruby and few C) whereas Python and Java do not do TCO.

    JavaScript language has confirmed using :) http://2ality.com/2015/06/tail-call-optimization.html

    0 讨论(0)
  • 2020-11-21 07:16
    1. We should ensure that there are no goto statements in the function itself .. taken care by function call being the last thing in the callee function.

    2. Large scale recursions can use this for optimizations, but in small scale, the instruction overhead for making the function call a tail call reduces the actual purpose.

    3. TCO might cause a forever running function:

      void eternity()
      {
          eternity();
      }
      
    0 讨论(0)
  • 2020-11-21 07:17

    Look here:

    http://tratt.net/laurie/tech_articles/articles/tail_call_optimization

    As you probably know, recursive function calls can wreak havoc on a stack; it is easy to quickly run out of stack space. Tail call optimization is way by which you can create a recursive style algorithm that uses constant stack space, therefore it does not grow and grow and you get stack errors.

    0 讨论(0)
提交回复
热议问题