Tail recursive vector sum

This question already has an answer here:

  • What is tail recursion? 23 answers

  • Your solution has two main problems:

  • The results are not accumulated - You simply call the vectorSum function without considering the result from previous calls.
  • The size of the problem is not reduced at each recursive call.
  • The are several ways to implement this recursion, I suggest the following approach:

    function result = vectorSum(v)
    %takes a vector v and the returns the sum of all elements in the vector
    if length(v) == 0
        result = 0;
    else
        result = v(end) + vectorSum(v(1:end-1));
    end
    end
    
    链接地址: http://www.djcxy.com/p/14166.html

    上一篇: python 3.x

    下一篇: 尾递归矢量和