我正在尝试在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]'s ?很明显,我处理的所有东西都是Ints的Lists。
发布于 2013-02-22 01:04:42
您的理解实际上是生成List[List[Int or ListInt]],因此推断的类型是List[ListAny]。下面是来自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)))https://stackoverflow.com/questions/15007738
复制相似问题