Question

I have the following function using the scalaz |+| operator:

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

Adding two maps manually works flawlessly (a: Map[String, Int) |+| b: Map[String, Int]), but declaring the above function yields 3 errors:

<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(_ |+| _)

Why doesn't this work and how can I fix this?

Was it helpful?

Solution

Have a look at the foldLeft API, it takes two argument lists. The first one is the initial value of the fold, the second one the reducing function.

I think you probably want

import scalaz._
import Scalaz._

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

If you know that your list is non-empty you could also use games.reduce(_ |+| _).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top