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. For example, Int values are combined using addition by default, but multiplication is also associative and forms another Semigroup.


Now that you’ve learned about the Semigroup instance for Int, try to guess how it works in the following examples:

import arrow.*
import arrow.core.extensions.*

Int.semigroup().run { 1.combine(2) }
// 3
import arrow.core.*
import arrow.core.extensions.*
import arrow.core.extensions.listk.semigroup.*

ListK.semigroup<Int>().run {
  listOf(1, 2, 3).k().combine(listOf(4, 5, 6).k())
// [1, 2, 3, 4, 5, 6]
import arrow.core.*
import arrow.core.extensions.option.semigroup.semigroup

Option.semigroup(Int.semigroup()).run {
// Some(3)
Option.semigroup(Int.semigroup()).run {
// Some(1)

Many of these types have methods defined directly on them, which allow for this example of combining: + on List. But the value of having a Semigroup typeclass available is that these compose.

Additionally, Semigroup adds + syntax to all types for which a Semigroup instance exists:

Option.semigroup(Int.semigroup()).run {
  Option(1) + Option(2)
// Some(3)

Contents partially adapted from Scala Exercises Cat’s Semigroup Tutorial

Data types

Module Data types
arrow.core AndThen, Const, Either, Function0, Function1, Id, ListK, MapK, NonEmptyList, Option, SequenceK, SetK, Try, Tuple2
arrow.fx IO, Resource, Schedule

Type Class Hierarchy

Do you like Arrow?

Arrow Org