注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

随机过程

http://superware.blog.163.com

 
 
 

日志

 
 

Tail Recursive  

2015-07-16 10:24:55|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |


    A function call is said to be tail recursive if there is nothing to do after the function returns except return its value.

    Since the current recursive instance is done executing at that point, saving its stack frame is a waste. Specifically, creating a new stack frame on top of the current, finished, frame is a waste.

    A compiler is said to implement tail recursion if it recognizes this case and replaces the caller in place with the callee, so that instead of nesting the stack deeper, the current stack frame is reused. This is equivalent in effect to a GoTo, and lets a programmer write recursive definitions without worrying about space inefficiency (from this cause) during execution. Tail recursion is then as efficient as iteration normally is.

Consider this recursive definition of the factorial function in C:

factorial(n) { if (n == 0) return 1; return n * factorial(n - 1); }



This definition is not tail-recursive since the recursive call to factorial is not the last thing in the function (its result has to be multiplied by n). But watch this:

factorial1(n, accumulator) { if (n == 0)

return accumulator; return factorial1(n - 1, n * accumulator); } factorial(n) { return factorial1(n, 1); }


The tail-recursion of factorial1 can be equivalently defined in terms of goto:

factorial1(n, accumulator) { beginning: if (n == 0)

return accumulator; else { accumulator *= n; n -= 1; goto beginning; } }

  评论这张
 
阅读(50)| 评论(0)
推荐

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017