-2
scala> var ard=new Array[Int](25)
ard: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0)

scala> ard(0)=0

scala> ard(1)=1

scala> def fibi(X:Int):Int = X match{
case 0 =>0
case 1 =>1
case _ => {
if (ard(X)!=0)
{
return ard(X)
}
else
{
return ard(X)=fibi(X-1)+fibi(X-2)
}
}
}
<console>:19: error: type mismatch;
 found   : Unit
 required: Int
       return ard(X)=fibi(X-1)+fibi(X-2)

I am getting Getting error mismatch when I try to assign ard(X)=fibi(x-1)+fibi(x-2) since fibi is returning a INT why am I getting a type error for it

1 Answers1

1

Assignment returns Unit in Scala, not the value and type of the thing assigned as in c. ( see e.g. What is the motivation for Scala assignment evaluating to Unit rather than the value assigned? )

To fix the type error, just do the assignment and return in separate steps.

def fibi(X:Int):Int = X match{
  case 0 =>0
  case 1 =>1
  case _ => {
    if (ard(X)!=0)
    {
      return ard(X)
    }
    else
    {
      ard(X)=fibi(X-1)+fibi(X-2)
      return ard(X)
    }
  }
}

p.s. consider indenting your code, omitting the unnecessary use of explicit return, and preventing stack growth with the @tailrec annotation.

Community
  • 1
  • 1
Steve Waldman
  • 13,689
  • 1
  • 35
  • 45
  • 1
    "preventing stack growth with the @tailrec annotation." The compiler compiles it as tail-recursive whether or not you have this annotation. The annotation is to cause an error when the function turns out to be non-tail--recursive. – The Archetypal Paul Jan 02 '17 at 08:52
  • @TheArchetypalPaul thanks! i didn't know that, but it's a good thing. – Steve Waldman Jan 02 '17 at 08:54