码迷,mamicode.com
首页 > 其他好文 > 详细

What is tail-recursion

时间:2014-05-08 17:35:09      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

Consider a simple function that adds the first N integers. (e.g. sum(5) = 1 + 2 + 3 + 4 + 5 = 15).

Here is a simple Python implementation that uses recursion:

def recsum(x):
 if x == 1:
  return x
 else:
  return x + recsum(x - 1)

 

If you called recsum(5), this is what the Python interpreter would evaluate.

bubuko.com,布布扣
recsum(5)
5 + recsum(4)
5 + (4 + recsum(3))
5 + (4 + (3 + recsum(2)))
5 + (4 + (3 + (2 + recsum(1))))
5 + (4 + (3 + (2 + 1)))
15
bubuko.com,布布扣

 

Note how every recursive call has to complete before the Python interpreter begins to actually do the work of calculating the sum.

Here‘s a tail-recursive version of the same function:

def tailrecsum(x, running_total=0):
  if x == 0:
    return running_total
  else:
    return tailrecsum(x - 1, running_total + x)

 

Here‘s the sequence of events that would occur if you called tailrecsum(5), (which would effectively be tailrecsum(5, 0), because of the default second argument).

bubuko.com,布布扣
tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
15
bubuko.com,布布扣

 

In the tail-recursive case, with each evaluation of the recursive call, the running_total is updated.

What is tail-recursion,布布扣,bubuko.com

What is tail-recursion

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/yuyutianxia/p/3715747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!