我正试图使用以下代码创建一个不可变的哈希映射[String,(String,Int(]:
def genList(xx: String) = {
Seq("one", "two", "three", "four")
}
val oriwords = Set("hello", "how", "are", "you")
val newMap = (Map[String, (String, Int)]() /: oriwords) (
(cmap, currentWord) => {
val xv = 2
genList(currentWord).map(ps => {
val src = cmap get ps
if(src == None) {
cmap + (ps -> ((currentWord, xv)))
}
else {
if(src.get._2 < xv) {
cmap + (ps -> ((currentWord, xv)))
}
else cmap
}
})
}
)
有了这个代码,我得到了以下异常:
error: type mismatch;
found : Seq[scala.collection.immutable.Map[String,(String, Int)]]
required: scala.collection.immutable.Map[String,(String, Int)]
genList(currentWord).map(ps => {
^
我知道它正在返回Map[String, (String, Int)]
的list
,而不是针对折叠操作的Map[String, (String, Int)]
的更新。不幸地我得到了任何关于如何修复它的建议。我是Scala的新手。
预期输出为:
scala.collection.immutable.Map[String,(String, Int)] = Map(one -> (are,2), two -> (are,2), three -> (are,2), four -> (are,2))
使用fold:
def genList(xx: String) = {
Seq("one", "two", "three", "four")
}
val oriwords = Set("hello", "how", "are", "you")
val newMap = (Map[String, (String, Int)]() /: oriwords) (
(cmap, currentWord) => {
val xv = 2
genList(currentWord).map(ps => {
val src = cmap get ps
if(src == None) {
cmap + (ps -> ((currentWord, xv)))
}
else {
if(src.get._2 < xv) {
cmap + (ps -> ((currentWord, xv)))
}
else cmap
}
}).fold(Map[String, (String, Int)]())((a, b) => a ++ b)
}
)
println(newMap) //Map(one -> (hello,2), two -> (hello,2), three -> (hello,2), four -> (hello,2))
foldLeft
返回的累加器类型为Seq[Map[String, (String, Int)]]
,而它应该是Map[String, (String, Int)]
如上所述,原因是您在返回Seq
的Seq
上调用map
。你可以使用foldLeft 来解决这个问题
def genList(xx: String) = {
Seq("one", "two", "three", "four")
}
val oriwords = Set("hello", "how", "are", "you")
val newMap = (Map[String, (String, Int)]() /: oriwords) (
(cmap, currentWord) => {
val xv = 2
genList(currentWord).foldLeft(cmap) {
(acc, ps) => {
val src = acc get ps
if (src == None) {
acc + (ps -> ((currentWord, xv)))
}
else {
if (src.get._2 < xv) {
acc + (ps -> ((currentWord, xv)))
}
else acc
}
}
}
}
)
println(newMap)
Map(one -> (hello,2), two -> (hello,2), three -> (hello,2), four -> (hello,2))
然而,输出与预期值不匹配,因此您需要检查您的逻辑。。。