[英]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()使用 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.如果我只是使用 List 的第一个 to 元素运行它,它会按预期工作。
@ scala.math.pow(1,2)
res28: Double = 1.0
Furthermore, the function definition in the repl (amm) shows that it's expecting doubles.此外,repl (amm) 中的 function 定义表明它期待双倍。
@ scala.math.pow <tab>
def pow(x: Double, y: Double): Double
So, why am I getting an error found Double, required Int
?那么,为什么我会
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.但我收到相同的错误消息。
If you check the type signature of foldLeft
you can see that it looks like this:如果您检查
foldLeft
的类型签名,您会看到它看起来像这样:
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 .所以初始值是Int类型的
1
,所以 function 应该是(Int, Int) => Int类型,所以 function 应该返回一个Int ,但它返回一个Double 。
You can fix it either like this:您可以像这样修复它:
(returns an Int ) (返回一个Int )
List(1,2,3).foldLeft(1) {
case (acc, x) => math.pow(acc, x).toInt
}
Or like this:或者像这样:
(returns a Double ) (返回一个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
;顺便说一句,两个选项都将返回
1
,因为1^x
总是返回1
; which is not probably what you want, which probably means you do not understand how foldLeft
works.这可能不是您想要的,这可能意味着您不了解
foldLeft
工作原理。 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 .此外,这与Ammonite无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.