我是 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編譯器將失敗,因為這個錯誤的括號使其非尾遞回,因此它也有助于發現問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/413845.html
標籤:
