【问题标题】:Scala reduceList failing because of type mismatch requiring java.io.Serializable由于需要 java.io.Serializable 的类型不匹配,Scala reduceList 失败
【发布时间】:2017-04-22 14:30:16
【问题描述】:

我正在尝试将列表与以下功能结合起来:

def merge(first: List[(Char, Int)], other: List[(Char, Int)]): List[List[(Char, Int)]] = 
  first.flatMap(tpl => other map (tpl2 => List(tpl, tpl2)))

def combine(l: List[List[(Char, Int)]]): List[List[(Char, Int)]] = l reduceLeft merge

不幸的是,我收到以下编译器消息:

错误:类型不匹配;
找到:(List[(Char, Int)], List[(Char, Int)]) => List[List[(Char, Int)]]
必需:(List[Product with java.io.Serializable], List[(Char, Int)]) => List[Product with java.io.Serializable]
l reduceLeft 合并

我了解减少List[Int] 只能生成Int 的结果。就我而言,我有List[List[(Char, Int)]],所以我希望我可以生成List[(Char, Int)] 的结果。谁能帮我理解我的代码有什么问题?

【问题讨论】:

  • 您正在映射其他元素并将tpl 添加到other 元组列表的所有元素中?
  • 是的,如果 first = List(('a',1)) and other = List(('b',1), ('b',2)) 它会返回列表(列表(('a',1),('b',1)), 列表(('a',1),('b',2)))

标签: scala


【解决方案1】:

reduceLeft的定义:

def reduceLeft[B >: A](op: (B, A) ⇒ B): B

所以你的函数 merge 必须返回 List[(Char, Int)] 而不是 List[List[(Char, Int)]] .此外,您的函数 combine 将返回 List[(Char, Int)],因为它减少了 List 内的 List。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多