## 计算字母的出现次数，并将字典放在列表中内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (35)

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

### 1 个回答

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