i have a next code
val listOption: List[Option[Int]] = List(1.some, none, 2.some)
i want to fold elements, i write the next code
val result = listx.fold(0.some)((acc, el) => {
(acc, el) match {
case (Some(a), Some(b)) => Some(a + b)
case (Some(a), _) => Some(a)
case (_, Some(b)) => Some(b)
case _ => el
}
})
println(result.getOrElse(0)) // => 3
this workds fine, but i see in scalaz sources the next tric
val composeFold = Foldable[List] compose Foldable[Option]
composeFold.fold(listOption) // => 3
But i do not understand how it correct work, and why scalaz not mix this methods into listOption instance, and what differenct between scala fold and scalaz fold
The scalaz
foldfunction uses theMonoidinstance of the elements, so you don't have to supply a start value and a function to combine the elements.A
Monoidhas two functionszero/emptyandappend/combine. ForIntthis could be :Using this
Monoid[Int]we can write the Scalazfoldas a Scalafold:We can combine the
Foldable[List]andFoldable[Option]like you showed :You can use the
foldablesyntax import and useconcatenateorsuml/sumr(There is alsofoldbut it clashes withList.foldandOption.fold) :Instead of the specific imports like
scalaz.std.list._andscalaz.syntax.foldable._, you could also use the uber imports withimport scalaz._, Scalaz._.