Using monoids

Using Scalaz monoids is pretty straightforward. Here is an example program:

import scalaz._import Scalaz._object MonoidsExample {  def main(args: Array[String]): Unit = {    val numbers = List(1, 2, 3, 4, 5, 6)    System.out.println(s"The sum is: ${numbers.foldMap(identity)}")    System.out.println(s"The product (6!) is:     ${numbers.foldMap(Tags.Multiplication.apply)}")    val strings = List("This is\n", "a list of\n", "strings!")    System.out.println(strings.foldMap(identity)(stringConcatenation))  }}

The imports in our code make sure that we can call foldMap on our list of numbers. If we run this example, we will get the following output:

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.