Scala:尾递归功能

问题描述 投票:1回答:2

结果总是得到“1”。 :( 这个功能怎么了?

    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)
    }
function scala tail-recursion pow
2个回答
7
投票

你必须更换所以:case 0 => result


0
投票

可能与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)
}
© www.soinside.com 2019 - 2024. All rights reserved.