September 2018
Intermediate to advanced
398 pages
9h 43m
English
This is interesting—how can we use Monoid in our day-to-day programs? The most compelling use case is to fold data structures. When you have Monoid[A], it is trivial to combine all of the elements of Vector[A] to obtain one A. For instance, we can get the sum of all of the elements of Vector[Int], as follows:
Vector(1,2,3).combineAll // res8: Int = 6
This is equivalent to calling foldLeft on Vector:
Vector(1, 2, 3).foldLeft(0) { case (acc, i) => acc + i }
Indeed, foldLeft accepts two arguments, as follows:
Cats also provide a foldMap function, which lets you transform the elements of a collection into ...
Read now
Unlock full access