我正在研究"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 > 0
则n < 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
是一个表达式,因此提供了一个(类型化的(值。
考虑函数f
和g
,如下所示:
def f() = if (1==2) "whow!"
f: ()Any
def g() = if (1==2) "whow!" else "ok!"
f: ()String
请注意推断的返回类型。在函数f
中,假定else
部分(未声明(返回Unit
类型。因此,在这种情况下,Unit
和 String
之间的兼容类型是 Any
。
这与类型仅为 String
的函数g
形成对比。