斯卡拉尾递归

2 scala tail-recursion pattern-matching

我在scala中有一个函数,我想知道是否有可能进入尾递归函数.

def get_f(f: Int => Int, x: Int, y: Int): Int = x match {
  case 0 => y
  case _ => f(get_f(f, x - 1, y))
}
Run Code Online (Sandbox Code Playgroud)

Mur*_*fin 6

我看到这个函数将函数应用于f递归的结果,x时间.这是一样的把它应用到y,x倍.另外我建议你使用if else而不是模式匹配.

@tailrec
def get_f(f: Int => Int, x: Int, y: Int): Int = 
    if(x == 0) y
    else get_f(f, x - 1, f(y))
Run Code Online (Sandbox Code Playgroud)

添加@tailrec注释以确保它是尾递归