jmcneirney
jmcneirney

Reputation: 1384

Type mismatch error when folding a List[Int] with scala.math.pow: found Double, required Int

I'm getting a type mismatch error when using math.pow()

@ List(1,2,3).foldLeft(1)( (x,y) => scala.math.pow(x,y) ) 
  cmd28.sc:1: type mismatch;
  found   : Double
  required: Int
  val res28 = List(1,2,3).foldLeft(1)( (x,y) => scala.math.pow(x,y) )
                                                        ^
  Compilation Failed

If I just run it with the first to elements of List it works as expected.

@ scala.math.pow(1,2) 
  res28: Double = 1.0

Furthermore, the function definition in the repl (amm) shows that it's expecting doubles.

@ scala.math.pow <tab>
 def pow(x: Double, y: Double): Double

So, why am I getting an error found Double, required Int? I've tried passing doubles and Ints

math.scala.pow(x.toDouble, y.toDouble) 

but I get the same error message.

Upvotes: 1

Views: 357

Answers (1)

If you check the type signature of foldLeft you can see that it looks like this:

def foldLeft[B](z: B)(op: (B, A) => B): B

So, let's see where you call it:

List(1,2,3).foldLeft(1)( (x,y) => scala.math.pow(x,y) )

So the initial value is a 1 of type Int, so the function should be of type (Int, Int) => Int, so the function should return an Int, but it returns a Double.

You can fix it either like this:
(returns an Int)

List(1,2,3).foldLeft(1) {
  case (acc, x) => math.pow(acc, x).toInt
}

Or like this:
(returns a Double)

List(1,2,3).foldLeft(1.0d) {
  case (acc, x) => math.pow(acc, x)
}

BTW, both options will return 1, because 1^x always returns 1; which is not probably what you want, which probably means you do not understand how foldLeft works. I would suggest you looking in the internet for a detailed explanation of how the operation is applied from left t right.
Also, this has nothing to do with Ammonite.

Upvotes: 3

Related Questions