Search code examples
scalascala-cats

Scala Cats documentation: Monoid[Pair[A,B]]


I've been away from Scala for several years (and never really got comfortable with it to begin with), instead working with languages that were (for me) easier to learn and work with.

I am now coming back and relearning it and experimenting with some of the libraries available. I have started looking at Cats recently but ran afoul of something early in the documentation that left me confused and wondering if I have (once again) missed something fundamental in the language.

On the page describing typeclasses we see the following:

For another motivating difference, consider the simple pair type.

final case class Pair[A, B](first: A, second: B)

Defining a Monoid[Pair[A, B]] depends on the ability to define a Monoid[A] and Monoid[B], where the definition is point-wise.

First, I don't know what the author means by "the definition is point-wise."

Second, I have no idea why defining Monoid[Pair[A, B]] would necessarily have to depend on defining a Monoid[A] and Monoid[B] (and it is never explained). There doesn't seem to be anything in the Monoid trait that would require it.


Solution

  • This has essentially nothing to do with Scala or any programming language at all. The author simply uses monoids as an (presumably well-known) example to demonstrate some feature of the framework.

    The assumption that an average reader of the Cats documentation will be somewhat familiar with monoids is not too far-fetched, because:

    The full sentence is

    Defining a Monoid[Pair[A, B]] depends on the ability to define a Monoid[A] and Monoid[B], where the definition is point-wise.

    This sentence is using monoids as an example, in order to demonstrate something about typeclasses. What it probably wanted to say is:

    Let (A, op_A, 1_A) and (B, op_B, 1_B) be two monoids. Then the cartesian product A x B can also be endowed with a structure of a monoid in a natural way as follows:

                         1_{AxB} := (1_A, 1_B)
      (a1, b1) op_{AxB} (a2, b2) := (a1 op_A a2, b1 op_B b2)
    

    The sentence says that the defintion is "pointwise". I think the word "componentwise" would have been much more appropriate. Wikipedia article uses "pairwise" for whatever reason. I would prefer "componentwise" over both "pointwise" and "pairwise" here.