2

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)

}

5
  • What makes you think it is receiving a Unit? Your function is defined as returning an Int, so you're definitely getting an Int back, how did you determine that you're getting Unit back? Commented Sep 30, 2012 at 4:43
  • I made an edit. Elipse is telling me that. Commented Sep 30, 2012 at 5:06
  • 2
    You should consider to accept some answers if they help to resolve your problems Commented Sep 30, 2012 at 6:08
  • 1
    Please do not violate the Honor code principles you agreed. This is a homework assignment coming from Functional Programming Principles in Scala online course. Commented Sep 30, 2012 at 8:10
  • I am not violating the honor code. Commented Oct 2, 2012 at 8:33

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So pascal looks at count(r,c,1,0) first and says this is a unit instead of realizing that it calls a local function that returns an int?
Luigi was saying that the def inside the function actually gets evaluated and returns Unit. I've edited the answer to make that a little bit more clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.