[英]Scala assumes wrong type when using foldLeft
我正在尝试在Scala中创建叉积函数,其中k
是构建叉积的次数。
val l = List(List(1), List(2), List(3))
(1 to k).foldLeft[List[List[Int]]](l) { (acc: List[List[Int]], _) =>
for (x <- acc; y <- l)
yield x ::: l
}
但是,此代码无法编译:
test.scala:9: error: type mismatch;
found : List[List[Any]]
required: List[List[Int]]
for (x <- acc; y <- l)
^
为什么会认为我有一个List[Any]
呢? 显然,我要处理的所有内容都是Int
的List
。
您的理解力是有效地产生List [List [Int或List [Int]]],因此推断的类型为List [List [Any]]。 这是来自repl的示例:
scala> val l = List(List(1), List(2), List(3))
l: List[List[Int]] = List(List(1), List(2), List(3))
val x = for {
| x <- l
| y <- l
| } yield x ::: l
x: List[List[Any]] = List(List(1, List(1), List(2), List(3)), List(1, List(1), List(2), List(3)), List(1, List(1), List(2), List(3)), List(2, List(1), List(2), List(3)), List(2, List(1), List(2), List(3)), List(2, List(1), List(2), List(3)), List(3, List(1), List(2), List(3)), List(3, List(1), List(2), List(3)), List(3, List(1), List(2), List(3)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.