user1656125
user1656125

Reputation: 107

Recursive function not returning Int

I have a recursive function that will repeat the function until the if condition is not met then output an integer. However the function outside this function that requires an integer is receiving a unit. How should I modify the code in order to return an 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)
   }

This is the whole program

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)

}

Upvotes: 2

Views: 595

Answers (1)

Luigi Plinge
Luigi Plinge

Reputation: 51109

The value returned from pascal is the last expression it contains. You want it to be your evaluation of count but that's not the last thing. Assignments (def, val etc) are of type Unit, as you've discovered:

  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
  }

Just move count(r,c,1,0) after the def and that should fix the problem.

Upvotes: 6

Related Questions