Search code examples
scalafunctional-programmingmonoidsscala-cats

Monoid instance for A => A in Cats


Functions A => A are monoid with identity as empty and composition as combine. Unfortunately I did not find it in cats library. Does the library provide a monoid instance for these functions ?

What about A => M[A], where M is a monad or applicative ?


Solution

  • Cats has a Monoid instance of A => A in instances/function.scala.

    A => M[A] for a Monad M seams to form form a Monoid with a => M.pure(a) as empty the following combine op:

    def compose(f1 = A => M[A], f2 = A => M[A]): A => M[A] =
      a => f1(a).flatMap { e => f2(e) }
    

    This does does not apeart to be implemented in the library.
    Proof of Monoid laws left as an exersise for the reader.