When to use monoids

In the preceding examples, we showed how to use monoids in order to achieve certain things. However, if we look at the previous example, we could simplify it in the following way:

object FeatureCountingOneOff {  def main(args: Array[String]): Unit = {    val features = Array("hello", "features", "for", "ml", "hello",     "for", "features")    System.out.println(s"The features are: ${      features.foldLeft(Map[String, Int]()) {        case (res, feature) => res.updated(feature,         res.getOrElse(feature, 0) + 1)      }    }")  }}

In fact, each example could be rewritten to a representation similar to the preceding code.

While someone might be tempted to do things this way, it might not always be scalable. As we already mentioned, the purpose of monoids is ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.