A semigroup for some given type
A has a single operation (which we will call
combine), which takes two values of type
A, and returns a value of type
A. This operation must be guaranteed to be associative. That is to say that:
must be the same as
for all possible values of a, b ,c.
There are instances of
Semigroup defined for many types found in Arrow and the Kotlin std lib.
Int values are combined using addition by default but multiplication is also associative and forms another
Now that you’ve learned about the Semigroup instance for Int try to guess how it works in the following examples:
import arrow.typeclasses.* semigroup<Int>().combine(1, 2) // 3
import arrow.data.* ListK.semigroup<Int>().combine(listOf(1, 2, 3).k(), listOf(4, 5, 6).k()) // ListK(list=[1, 2, 3, 4, 5, 6])
import arrow.core.* Option.monoid<Int>().combine(Option(1), Option(2)) // Some(3)
Option.monoid<Int>().combine(Option(1), None) // None
Many of these types have methods defined directly on them, which allow for such combining, e.g.
List, but the value of having a
Semigroup typeclass available is that these compose.
Contents partially adapted from Scala Exercises Cat’s Semigroup Tutorial