scala - 为什么这个 foldLeft scala 代码不起作用?
问题描述
以下代码片段旨在为我提供Map[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 -> (w, xv))
}
else {
if(src.get._2 < xv) {
cmap + (ps -> (w, xv))
}
else cmap
}
})
}
)
但我收到以下错误:
error: too many arguments for method ->: (y: B)(String, B)
cmap + (ps -> (w, xv))
^
更新:通过答案中提到的建议更改,上述错误被删除。
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 => {
^
解决方案
ps -> (w, xv)
被解释为
ps.->(w, xv)
即作为传递两个参数而不是你想要的,这是传递一个 2 元组作为单个参数:
ps.->((w, xv))
或在运算符语法中:
ps -> ((w, xv))