我正在尝试计算字符串流中字母的出现次数,然后为列表中的每个字符串放置映射( "letter"->计数)。
def checksum(ipt: Stream[String]) = ipt.foldLeft(List(Map("x"->1)))( (n:
List[Map[String, Int]], m: String) => n ++
m.split("").groupBy(identity).mapValues(_.size).toMap)
它给出了问题:
Expression of type List[Equals] doesn't conform to expected type List[Map[String, Int]]
怎么了?就像对每个字符串都这样做没有问题:
def checksum(ipt: Stream[String]) = ipt.foreach( (m: String) => println(m.split("").groupBy(identity).mapValues(_.size)))
它提供了类似这样的东西
val s = "bababc"
val d = "abbcde"
checksum(List(s,d).toStream)
out:
Map(b -> 3, a -> 2, c -> 1)
Map(e -> 1, a -> 1, b -> 2, c -> 1, d -> 1)
但是现在我该如何在列表中隐藏所有这些地图呢?我不能使用vars,需要在一个表达式中使用它。
发布于 2019-03-26 03:51:10
如果每个字符串都需要一个map,您可以使用第一个流上的map函数来实现,如下所示:
def checksums(ipt: Stream[String]): Stream[Map[Char, Int]] = {
ipt.map(checksum)
}
def checksum(ipt: String): Map[Char, Int] = ipt.foldLeft(Map.empty[Char, Int]) { case (acc, ch) =>
acc.get(ch) match {
case Some(q) => acc + (ch -> (q + 1))
case None => acc + (ch -> 1)
}
}
返回到您的代码,向列表添加元素的操作符是:+,而不是++。
++用于连接列表。
所以你可以像这样修复你的代码:
def checksumFixed(ipt: Stream[String]) = {
ipt.foldLeft(List(Map("x"->1))) { (n: List[Map[String, Int]], m: String) =>
n :+ m.split("").groupBy(identity).mapValues(_.length)
}
}
https://stackoverflow.com/questions/55344949
复制相似问题