【问题标题】:Applying fold function on a List of HashMap and return a List of another type in Scala在 HashMap 列表上应用折叠函数并在 Scala 中返回另一种类型的列表
【发布时间】:2022-02-23 22:24:26
【问题描述】:

我正在尝试在包含不同类型元素的列表上使用折叠功能。 这是我的代码的简化版本:

val list: List[Int] = List(1, 1, 1, 1)
val listOfMap: List[Map[String, Int]]= List(Map("a" -> 1), Map("a" -> 2))

def addN(list: List[Int], n: Int) = list.map(_+n)

val result = listOfMap.fold(list)((x, y) => addN(x, y("a")))

我期待result 将是一个整数列表:

List(4, 4, 4, 4)

但是,我得到的错误是类型不匹配:

x:必需:List[Int],找到:Iterable[Any] with Partial Function[Int with String, Int] with Equals

"a":必需:Int with String, Found String

【问题讨论】:

标签: list scala hashmap fold


【解决方案1】:

弃牌不要按照你的想法去做。 对于此类问题,Scala 标准库文档是您的朋友:https://www.scala-lang.org/api/2.13.3/index.html

def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1

使用指定的关联二元运算符折叠此集合的元素。

你需要 foldLeft 代替

def foldLeft[B](z: B)(op: (B, A) => B): B

将二元运算符应用于起始值和该序列的所有元素,从左到右。

注意:对于无限大小的集合不会终止。

在你的情况下

val result = listOfMap.foldLeft(list)((x, y) => addN(x, y("a")))
//List(4, 4, 4, 4): scala.collection.immutable.List[scala.Int]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2018-12-06
    • 2011-04-13
    • 1970-01-01
    • 2023-01-04
    相关资源
    最近更新 更多