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

scala tail recursive优化,复用函数栈

时间:2014-10-18 20:59:44      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   使用   sp   div   on   

在scala中如果一个函数在最后一步调用自己(必须完全调用自己,不能加其他额外运算子),那么在scala中会复用函数栈,这样递归调用就转化成了线性的调用,效率大大的提高。
If a function calls itself as its last action, the function‘s stack frame can be reused. This is called tail recursion.
=> Tail recursive functions are iterative process

这里实现了两个版本的阶乘函数,一个是普通的写法,另外一个使用了tail recursive的优化
/*
In Scala, only directly recursive call to the current function are optimized.
One can require that a function is tail-recursive using a @tailrec annotation:
   @tailrec
   def gcd(a: Int, b: Int): Int = ...
If the annotation is given, and the implementation of gcd were not
tail recursive, an error would be issued.
*/

import scala.annotation.tailrec

object exercise {

  def factorial(n: Int): Int =
    if (n == 0) 1 else n * factorial(n-1)

  //a tail recursive version of factorial
  def factorialTailRecursion(n: Int): Int = {
    @tailrec
    def loop(acc: Int, n: Int): Int =
      if (n == 0) acc
      else loop(acc * n, n-1)
      loop(1, n)
  }

  factorial(4)
  factorialTailRecursion(4) //optimized! the function‘s stack frame can be reused!
}

 

scala tail recursive优化,复用函数栈

标签:style   blog   color   io   ar   使用   sp   div   on   

原文地址:http://www.cnblogs.com/yanghuahui/p/4033563.html

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