[英]Scala: Tail recursive power function
結果我總是得到“1”。 :(
這個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
可能與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)
}
更好的尾遞歸解決方案(堆棧安全)可能如下所示:
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
}
}
我是 Scala 的新手,我有同樣的任務,喜歡match的想法。 以您的代碼為例,這就是我所擁有的
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)
}
}
還不知道@tailrec是什么意思,但我想它可能有用,IDEA 暗示了我這一點:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.