# Diving into Scala Cats – Semigroups

### In this article, we'll dive into Cats to understand Semigroup type class.

· Java Zone · Tutorial
Save
2.14K Views

New to Cats? No worries, go through my previous article Getting Started with Scala Cats to understand how amazing Cats is.

In this article, we will cover the concepts and implementation of Semigroups in Cats.

## What are Semigroups?

In functional programming terms a Semigroup is a concept which encapsulates aggregation with an associative binary operation.

The Semigroup type class comes with a method combine which simply combines two values of same data type by following the principle of Associativity.

combine method is constructed as:

Scala

x

1
trait Semigroup[A] {
2
def combine(x: A, y: A): A
3
}

and can be implemented as:

Scala

xxxxxxxxxx
1

1
// The type class definition
2
import cats.kernel.Semigroup
3

4
// Import type class instance for type Int
5
import cats.instances.int._
6

7
// The combine implementation for Int is by default addition
8
val onePlusTwo = Semigroup[Int].combine(1, 2)

Infix syntax is also available for types that have a Semigroup instance:

Scala

xxxxxxxxxx
1

1
import cats.implicits._
2

3
1 |+| 2

## Associativity is the only law for Semigroup

combine holds associativity that means the following equality must hold for any choice of x, y, and z.

Scala

xxxxxxxxxx
1

1
combine(x, combine(y, z)) = combine(combine(x, y), z)

Associativity allows us to partition the data any way we want and potentially parallelize the operations.

For example, for a given list of numbers: 1, 2, 3, 4, 5 we can do something like this:

Scala

xxxxxxxxxx
1

1
// Could run in different threads
2
val group1 = Semigroup[Int].combine(1, 2)
3
val group2 = Semigroup[Int].combine(3, 4)
4
val group3 = Semigroup[Int].combine(group1, group2)
5
val total  = Semigroup[Int].combine(group3, 5)

## Writing a custom Semigroup

The combine implementation for Int will add the two parameters. What if we want to multiply two numbers? We can write our own implementation:

Scala

xxxxxxxxxx
1

1
implicit val multiplicationSemigroup = new Semigroup[Int] {
2
override def combine(x: Int, y: Int): Int = x * y
3
}
4

5
// uses our implicit Semigroup instance above
6
val four = Semigroup[Int].combine(2, 2)

Cats allows to provide implementation of combine in more concise ways:

Scala

xxxxxxxxxx
1
10

1
implicit val multiplicationSemigroup: Semigroup[Int] = (x: Int, y: Int) => x * y
2

3
// or more succinctly
4
implicit val multiplicationSemigroup: Semigroup[Int] = (x, y) => x * y
5

6
// or even
7
implicit val multiplicationSemigroup: Semigroup[Int] = _ * _
8

9
// or even more verbose
10
implicit val multiplicationSemigroup = Semigroup.instance[Int](_ * _)

We can easily provide our own implementation of combine for Semigroup instances of all the common types in Scala ecosystem.

## Semigroups with strings

Cats implementation for String concatenates the two parameters. But that implementation doesn’t include a space between them. What if I want to add a space between the strings?

Scala

xxxxxxxxxx
1

1
implicit val customStringSemigroup = Semigroup.instance[String](_ + " " + _)
2

3
Semigroup[String].combine("john", "doe")
4
// results: String = "john doe"

## Semigroups with collections

Given the associative constraint we can build more useful constructs from the simple combine(x, y) method.

We can use recursion directly or make use of Scala’s fold() to operate on a collection of values:

Scala

xxxxxxxxxx
1

1
def combineStrings(collection: Seq[String]): String = {
2
collection.foldLeft("")(Semigroup[String].combine)
3
}

However, given just Semigroup we cannot write the above expression generically.

## Limitation of Semigroups

We quickly run into issues if we try to write a generic method combineAll(collection: Seq[A]): [A] for the above expression, because the fallback value will depend on the type of (”” for String, 0 for Int, etc).

There is a solution to this problem though, it’s called the Monoid.

We’ll learn about Monoids in our next article – Diving into Scala Cats – Monoids. Stay tuned!!!

## References

The best two Scala Cats resources I know are here:

Topics:
scala, cats, functinal programming

Published at DZone with permission of Mansi Babbar.

Opinions expressed by DZone contributors are their own.