Scala 尾递归到非尾递归 [英] Scala Tail Recursive to Not Tail Recursive

查看:64
本文介绍了Scala 尾递归到非尾递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个奇怪的问题,但是...

This may be a weird question but...

问题:如何将 Scala 中的尾递归函数转换为非尾递归解决方案?

Question: How do I turn a tail-recursive function in Scala into a non-tail-recursive solution?

注意:我知道尾递归解决方案在 Scala 中很棒,但我被要求将其更改为非尾递归解决方案.我不知道该怎么做

Note: I am aware tail recursive solutions are great in Scala, but I was asked to change it into a non-tail recursive solution. I have no idea how to do that

我在这里有我的尾递归解决方案代码(至少我希望它是尾递归,哈哈)

I have my code for a tail-recursive solution here (at least I hope it's tail recursive lol)

def cubesTailRecur(a: List[Int], acc: List[Int] = List.empty): List[Int] = {
      a match {
        case Nil => acc
        case h :: t if (h%2 == 0) => cubesTailRecur(t, acc)
        case h :: t  => cubesTailRecur(t, acc :+ Math.pow(h, 3).toInt)
      }
    }

我的函数所做的是遍历给定的整数列表,并返回一个包含所有奇数立方体的新数组.

What my function does is iterate through a given List of integers and returns a new array with the cubes of all the odd numbers.

示例:

    println(cubesTailRecur(List(1, 2, 3, 4, 5, 6, 7)))

    // OUTPUT
    // List(1, 27, 125, 343)

推荐答案

尾递归是一种递归形式,其中递归调用是最后一条指令.不进行尾递归意味着您需要对递归调用的结果进行一些其他计算.

Tail recursion is a form of recursion in which recursive call is the last instruction. To not make something tail recursive would mean that you need to do some other computation with the result of the recursive call.

在您的情况下,您可以删除 acc/accumulator 参数并通过递归堆栈执行累加.大致如下,

In your case, you can remove the acc/accumulator parameter and perform accumulation through recursive stack. Something along the following lines,

def cubesRec(a: List[Int]): List[Int] = a match {
  case Nil => List[Int]()
  case h::t if (h%2 == 0) => cubesRec(t)
  case h::t => Math.pow(h,3).toInt :: cubesRec(t)
}

这篇关于Scala 尾递归到非尾递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆