Scala 递归:返回 vs if/else 控制



我正在研究"Scala for the Impatient",其中一个练习要求编写一个函数来计算x^n(通过重复平方的方法(,而无需使用 return 关键字。我的第一个想法如下:

def power(x: Double, n: Int): Double = {
    if(n > 0) {
        if (n % 2 != 0)  x * power(x, n-1) // adding a return works!
        else power(x, n/2) * power(x, n/2) // adding a return works!
    }
    if(n < 0) 1/power(x, -n)               // adding a return works!
    else 1.0                               // adding a return works!
}

但是,这不起作用!起作用的是为每个案例添加回报。同样有效的还有以下几点:

def power(x: Double, n: Int): Double = {
    if(n > 0) {
        if (n % 2 != 0)  x * power(x, n-1)
        else power(x, n/2) * power(x, n/2)
    }
    else if(n < 0) 1/power(x, -n) 
    else 1.0
}

为什么我的第一次尝试无效?

如果n > 0n < 0为假,因此执行else 1.0
所以1.0如果n > 0就不应该被执行。

if(n > 0) {
    if (n % 2 != 0)  x * power(x, n-1)
    else power(x, n/2) * power(x, n/2)
}
else if(n < 0) 1/power(x, -n)
else 1.0   
注意在第

一个例子中,第一个if是空的,因为它对power的整体计算没有影响,因为它与主体中的其他if-else表达式无关:返回最后一个if-else的值。

作为旁注,在 Scala 中if-else是一个表达式,因此提供了一个(类型化的(值。

考虑函数fg,如下所示:

def f() = if (1==2) "whow!"
f: ()Any
def g() = if (1==2) "whow!" else "ok!"
f: ()String

请注意推断的返回类型。在函数f中,假定else部分(未声明(返回Unit类型。因此,在这种情况下,UnitString 之间的兼容类型是 Any

这与类型仅为 String 的函数g形成对比。

最新更新