/ scala

TOTD: Scala - Map as a Semigroup

You can use Semigroups to combine Maps in Scala. Semigroups abstract the combine operator. Its symbolic form is: |+|.

Map('b -> 3) |+| Map('a -> 2, 'c -> 42)

This yields:

Map('a -> 2, 'c -> 42, 'b -> 3)

Note that if keys match up, their values will be combined as Semigroups. This means that if you have a key b -> 1 in the first Map and a b -> 2, this will yield b -> 3 because the default combine operation for integers is +.

To get this to work using Cats, bring in these modules:

import cats.syntax.monoid._ // Needed for |+|
import cats.instances.map._ // we're working on Map
import cats.instances.int._ // Our Map values are Ints

Try this in a REPL near you. Try to combine a Tuple2[String, Int] (aka (String, Int)) and see if you can predict what you will get.