使用foldLeft时,Scala假定类型错误 [英] Scala assumes wrong type when using foldLeft

查看:79
本文介绍了使用foldLeft时,Scala假定类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Scala中创建叉积函数,其中k是构建叉积的次数.

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)
           ^

为什么曾经认为我有List[Any]?显然,我要处理的是IntList.

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

推荐答案

您的理解力实际上是产生List [List [Int或List [Int]]]],因此推断的类型是List [List [Any]].这是来自repl的示例:

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)))

这篇关于使用foldLeft时,Scala假定类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆