Bren
Bren

Reputation: 3686

Scala Error: identifier expected but '}' found

I'm trying to figure out this compile error:

Error:(51, 4) identifier expected but '}' found.
  } else if (n < 0) {
  ^

For this code:

def nthPowerOfX(n: Int, x:Double) : Double = {
  if (n == 0) {
     1.0
  } else if (n < 0) {
     1.0 / nthPowerOfX(n,x)
  } else if (n % 2 == 0 && n > 0) {
    nthPowerOfX(2, nthPowerOfX(n/2,x))
  } else {
    x*nthPowerOfX(n-1, x)
  }
}

I tried return statements too but that didn't help nor should it matter to my understanding.

Upvotes: 1

Views: 3917

Answers (1)

Bartek
Bartek

Reputation: 134

Jozef is right! There is no error. Please consider using this:

  def nthPowerOfX(n: Int, x:Double) : Double = {
    n match{
      case 0 => 1.0
      case x if x < 0 => 1.0 / nthPowerOfX(n,x)
      case x if x % 2 == 0 && x > 0 => nthPowerOfX(2, nthPowerOfX(n/2,x))
      case x => x*nthPowerOfX(n-1, x)
    }
  }

But keep in mind that recursion is dangerous thing, it's better to use tail recursion, if we are talking about Scala.

Upvotes: 1

Related Questions