Scala assumes wrong type when using foldLeft

ⅰ亾dé卋堺 提交于 2019-12-13 03:07:54

问题


I am trying to create a cross product function in Scala, where k is the number of times I build the cross product.

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
}

However, this code does not compile:

test.scala:9: error: type mismatch;
    found   : List[List[Any]]
    required: List[List[Int]]
    for (x <- acc; y <- l)
           ^

Why does it ever think I have a List[Any]'s there? Clearly everything I am dealing with is Lists of Ints.


回答1:


Your for comprehension is effectively yielding List[List[Int or List[Int]]] hence the inferred type is List[List[Any]]. Here's an example from the 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/scala-assumes-wrong-type-when-using-foldleft

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!