递归函数不返回Int

use*_*125 2 recursion functional-programming scala

我有一个递归函数,它将重复该函数,直到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)
   }
Run Code Online (Sandbox Code Playgroud)

这是整个计划

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)
Run Code Online (Sandbox Code Playgroud)

}

Lui*_*hys 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
  }
Run Code Online (Sandbox Code Playgroud)

只要移动count(r,c,1,0) def和应该解决这个问题.