我是 Scala 的新手,我正在尝试定义一个尾递回阶乘函式,如下所示:
def anotherFactorial(n: Int): Int = {
def factHelper(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else factHelper(x - 1, x * accumulator)
factHelper(n, 1)
}
}
但它给了我一个不匹配的错误,说它找到了一个 Unit 型别而不是一个 Int 并且我看不到如何,我检查了其他 Scala 问题有同样的错误(比如这个:Scala Type Mismatch Unit 而不是 Int)但没有似乎我没有犯这些错误。
这是错误讯息:
type mismatch;
found : Unit
required: Int
}
uj5u.com热心网友回复:
错误的括号。你有:
def anotherFactorial(n: Int): Int = {
// the body with only def is Unit
def factHelper(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else factHelper(x - 1, x * accumulator)
factHelper(n, 1)
}
}
而不是
def anotherFactorial(n: Int): Int = {
// the body with only def is Unit
def factHelper(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else factHelper(x - 1, x * accumulator)
}
factHelper(n, 1)
}
我建议经常使用像scalafmt这样的格式化程序(例如在编译时)来立即发现这样的问题。此外,如果您注释factHelper
为@scala.annotation.tailrec
编译器将失败,因为这个错误的括号使其非尾递回,因此它也有助于发现问题。
0 评论