简体   繁体   English

Scala:尾递归幂 function

[英]Scala: Tail recursive power function

I always get "1" as result.结果我总是得到“1”。 :( :(
Whats wrong with this function?这个function有什么问题吗?

    def power(base: Int, exp: Int): BigInt = {
        def _power(result: BigInt, exp: Int): BigInt = exp match {
            case 0 => 1
            case _ => _power(result*base, exp-1)
        }
        _power(1, exp)
    }

您必须替换为: case 0 => result

probably not relevant for OP but I used this answer as an example for something and this version works: 可能与OP不相关,但我以以下答案作为示例,此版本有效:

def power(base: Int, exp: Int): BigInt = {
    def _power(result: BigInt, exp: Int): BigInt = exp match {
        case 0 => 1
        case 1 => result
        case _ => _power(result*base, exp-1)
    }
    _power(base, exp)
}

Better, tail-recursive solution (stack-safe) may look like:更好的尾递归解决方案(堆栈安全)可能如下所示:

def power(base: Int, exp: Int): BigInt {

  @scala.annotation.tailrec
  def loop(x: BigInt, n: Long, kx: BigInt): BigInt = {
    if (n == 1) x * kx
    else {
      if (n % 2 == 0)
        loop(x * x, n / 2, kx)
      else
        loop(x, n - 1, x * kx) // O(log N) time complexity!
    }
  }

  if (n == 0) 1
  else {
    val pow = loop(base, Math.abs(exp.toLong), 1)
    if (n > 0) pow else 1 / pow
  }

}

I'm new to Scala and I had the same task, liked the idea with match .我是 Scala 的新手,我有同样的任务,喜欢match的想法。 Used your code as an example and this is what I've got以您的代码为例,这就是我所拥有的

def power(base: Int, exp: Int): BigDecimal = {
  if (exp == 0) 1 else {
    @tailrec
    def _power(result: BigDecimal, exp: Int): BigDecimal = exp match {
      case 0 => result
      case pos if (pos > 0) => _power(result * base, exp - 1)
      case neg if (neg < 0) => _power(result / base, exp + 1)
    }

    _power(1, exp)
  }
}

Don't know what @tailrec means yet but I guess it may be useful, IDEA hinted me with that:)还不知道@tailrec是什么意思,但我想它可能有用,IDEA 暗示了我这一点:)

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

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