gpt4 book ai didi

scala - 我如何注释这个尾递归 Scala 函数

转载 作者:行者123 更新时间:2023-12-02 07:42:26 25 4
gpt4 key购买 nike

我有一个函数,我知道它是尾递归的。但是由于我定义它的方式,编译器提示该函数在非尾部位置进行递归调用。这是函数。

@tailrec
def travel: (Int, List[Char]) => Int = {
case (n, Nil) => n
case (n, '~' :: sls) => travel(0, sls)
case (n, '^' :: sls) => travel(max(n-1,0), sls)
case (n, '>' :: sls) => travel(n+1, sls)
case (_, s :: sls) => throw new IllegalArgumentException("Illegal selector '" + s + "'")
}

我明白了

error: could not optimize @tailrec annotated method travel: it contains a recursive call not in tail position
def travel: (Int, List[Char]) => Int = {

如果我这样写,它工作正常。

@tailrec
def travel(n:Int, l:List[Char]): Int = (n,l) match {
case (n, Nil) => n
case (n, '~' :: sls) => travel(0, sls)
case (n, '^' :: sls) => travel(max(n-1,0), sls)
case (n, '>' :: sls) => travel(n+1, sls)
case (_, s :: sls) => throw new IllegalArgumentException("Illegal selector '" + s + "'")
}

我认为这与 def: (Input) => Output = {} 类型声明风格有关。我使用它是因为它看起来比编写嵌套匹配或元组匹配更简洁。

最佳答案

两者不一样。在第一种情况下,方法产生一个函数,然后再次调用该方法(产生一个函数,等等)。也就是说,在第一种情况下,每次调用 travel 时,都会创建一个 Function1[(Int, List[Char]), Int] 的新实例。毫不奇怪,这不能转换为跳转指令。 (理论上可以,但分析会相当复杂,因为必须取消所有这些对象创建。)

第二种情况,只是方法调用自己,可以转化为跳转。

关于scala - 我如何注释这个尾递归 Scala 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9723235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com