【问题标题】:Scala assumes wrong type when using foldLeftScala 在使用 foldLeft 时假定类型错误
【发布时间】:2013-02-07 02:24:32
【问题描述】:

我正在尝试在 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]?显然,我正在处理的所有内容都是 Lists 或 Ints。

【问题讨论】:

    标签: scala syntax reduce fold


    【解决方案1】:

    您的 for 理解有效地产生 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)))
    

    【讨论】:

    • 啊!这只是一个错字:(,我看了一个小时。抱歉浪费了你的时间!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多