Diving into Scala Cats – Semigroups
In this article, we'll dive into Cats to understand Semigroup type class.
Join the DZone community and get the full member experience.Join For Free
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:
and can be implemented as:
Infix syntax is also available for types that have a
Associativity is the only law for Semigroup
combine holds associativity that means the following equality must hold for any choice of
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:
Writing a custom Semigroup
combine implementation for
Int will add the two parameters. What if we want to multiply two numbers? We can write our own implementation:
Cats allows to provide implementation of
combine in more concise ways:
We can easily provide our own implementation of
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?
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:
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
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!!!
You can download the learning template Scala Cats - Semigroups demonstrating the code implementations provided in this article.
The best two Scala Cats resources I know are here:
Published at DZone with permission of Mansi Babbar. See the original article here.
Opinions expressed by DZone contributors are their own.