0
在“Scala for Impatient”中解决了一个问题时,我遇到了一个让函数进入无限递归调用的场景,但我不知道为什么。无限递归函数
的问题是:
Write a function that computes x^n, where n is an integer. Use
the following recursive definition:
x^n = y^2 if n is even and positive, where y = x^(n/2)
x^n = x·x^(n – 1) if n is odd and positive
x^0 = 1
x^n = 1/x^–n if n is negative
Don’t use a return statement.
虽然我的回答是:
def positive(n: Int) = n > 0
def even(n: Int) = n % 2 == 0
def odd(n: Int) = !even(n)
def power(x: Double, n: Int) : Double = {
if (positive(n) && even(n)){
val y = power(x, n/2)
power(y, 2) // problematic part, if substituted by `y * y` it works, WHY??
}else if (positive(n) && odd(n)){
x * power(x, n-1)
}else if (n == 0){
1
}else{
1/power(x, -n)
}
}
我打算对此表示赞赏,但后来我意识到,在同一天提出的两个答案与提问没有答复。这不是强制性的评论,投票或回复,但你现在能够做出这些事情吗,穆罕默德?丹尼尔提供了一个值得接受的好答案吗? – halfer