我几乎可以肯定已经有了答案,但是作为 Scala 的初学者,我找不到它。
因此,我创建了一个power包含两个参数的函数:
def power(x: Double, n: Int): Double = {
@scala.annotation.tailrec
def go(acc: Double, i: Int): Double = {
if (i == 0) acc
else go(acc * x, i - 1)
}
go(1, n)
}
Run Code Online (Sandbox Code Playgroud)
如果我然后计算 power(2, 3)
println(
power(2, 3)
)
Run Code Online (Sandbox Code Playgroud)
我明白了8.0,这很好,但8如果第一个参数是,那就更好了Int。我怎样才能做到这一点?
您可以使用数字
def power[T](x: T, n: Int)(implicit num: Numeric[T]): T = {
import num._
@scala.annotation.tailrec
def go(acc: T, i: Int): T = {
if (i == 0) acc
else go(acc * x, i - 1)
}
go(fromInt(1), n)
}
power(2, 3) // 8: Int
Run Code Online (Sandbox Code Playgroud)
类型类的魔力
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |