我有一个递归函数,它将重复该函数,直到不满足if条件,然后输出一个整数。但是,此函数外部需要整数的函数正在接收一个单元。我应该如何修改代码以返回int?
count(r,c,1,0)
def count(r: Int, c: Int, countR: Int, lalaCount: Int): Int = {
if (countR < (r + 1)) count(r,c,countR + 1, lalaCount + countR)
else (lalaCount + c + 1)
}
这是整个计划
object hw1 {
def pascal(c: Int, r: Int): Int = {
count(r,c,1,0)
def count(r: Int, c: Int, countR: Int, lalaCount: Int): Int = {
if (countR < (r + 1)) count(r,c,countR + 1, lalaCount + countR)
else (lalaCount + c + 1)
}
} //On this line eclipse is saying "Multiple markers at this line
//- type mismatch; found : Unit required: Int
//- type mismatch; found : Unit required: Int
pascal(3,4)
}
答案 0 :(得分:6)
pascal
返回的值是它包含的最后一个表达式。你希望它是你对count
的评价,但这不是最后一件事。分配(def,val等)的类型为Unit,如您所见:
def pascal(c: Int, r: Int): Int = {
count(r,c,1,0) // => Int
def count(r: Int, c: Int, countR: Int, lalaCount: Int): Int = {
if (countR < (r + 1)) count(r,c,countR + 1, lalaCount + countR)
else (lalaCount + c + 1)
} // => Unit
}
在 count(r,c,1,0)
之后移动def
,这样可以解决问题。