简体   繁体   English

尾递归缺点运算符Scala

[英]Tail recursion cons operator Scala

If the last statement in a function is func(x,tailList): 如果函数中的最后一条语句是func(x,tailList):

    def func(x:Int):List[Int]...
    case head :: tailList => head :: func(x,tailList)

converting this function to tail recursion requires accumulator to be added as a third parameter (and to keep it clean adding a local function inside func() ). 将此函数转换为尾递归需要将累加器添加为第三个参数(并在func()内添加局部函数以使其保持整洁)。

    insertTail(x,tailList,head::acc) 

doesn't seem to work correctly. 似乎无法正常工作。 shouldn't "acc" hold the computation in progress? 不应“ acc”继续进行计算?

Am I missing something here to make it tail recursive work with accumulator? 我是否在这里缺少使累加器进行尾递归工作的内容?

Adding a more complete example 添加更完整的示例

def funcTailTest(x:Int,xs:List[Int]):List[Int] =  {
@tailrec
def inner(x:Int,xs:List[Int],acc:List[Int]) : List[Int] = xs match {

  case head::tailList => {
    inner(x,tailList,head::acc)
  }
}
inner(x,xs,Nil)

}

basically head should be added to the output of inner() function so w/o an attempt to make it tail recursive last statement in a case will look 基本上应该将head添加到inner()函数的输出中,以便在没有出现情况的情况下不尝试使其成为尾递归的最后一条语句

head::inner(x,tailList)

Following is a scala function to implement Tail recursion using cons operator 以下是使用cons运算符实现尾递归的scala函数

def reverseUtility(ele: List[Int], res: List[Int]):List[Int] ={
  ele match {
  case Nil => Nil
  case x :: Nil => x :: res
  case x :: y => reverseUtility(y, (x::res))
}}

Pass a list of Int and an empty list called res(result) as parameters for the function. 传递一个Int列表和一个称为res(result)的空列表作为该函数的参数。 Time complexity for the function is O(N) 该函数的时间复杂度为O(N)

Assuming that reverse is also tail recursively implemented (which it definitely can be), the following is a tail recursive append: 假设反向也是尾递归实现的(这肯定可以实现),则以下是尾递归追加:

def append[T](y: T, xs: List[T]): List[T] = {
  @tailrec
  def appendAcc[T](y: T, xs: List[T], acc: List[T]): List[T] = xs match {
    case Nil => y :: acc
    case x :: xs => appendAcc(y, xs, x :: acc)
  }

  appendAcc(y, xs, Nil).reverse
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM