Scalaz Map [String,Int]“summation”和foldLeft不起作用

时间:2013-11-16 15:23:42

标签: scala scalaz

我使用scalaz | + |有以下功能操作者:

  def sumGames(games: List[Map[String, Int]]) =
    games.foldLeft(_ |+| _)

手动添加两个地图完美无瑕(a:Map [String,Int] | + |) b:Map [String,Int]),但声明上述函数会产生3个错误:

<console>:20: error: missing parameter type for expanded function ((x$1, x$2) =>
 x$1.$bar$plus$bar(x$2))
           games.foldLeft(_ |+| _)
                          ^
<console>:20: error: missing parameter type for expanded function ((x$1: <error>
, x$2) => x$1.$bar$plus$bar(x$2))
           games.foldLeft(_ |+| _)
                                ^
<console>:20: error: missing arguments for method foldLeft in trait LinearSeqOpt
imized;
follow this method with `_' if you want to treat it as a partially applied funct
ion
           games.foldLeft(_ |+| _)

为什么这不起作用,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

看一下foldLeft API,需要两个参数列表。第一个是折叠的初始值,第二个是缩小函数。

我想你可能想要

import scalaz._
import Scalaz._

def sumGames(games: List[Map[String, Int]]) = 
  games.foldLeft(Map.empty[String, Int])(_ |+| _)

如果您知道列表非空,则还可以使用games.reduce(_ |+| _)