Abstract Algebra in Action: Semigroups and Monoids in C#
Many production problems are aggregation problems in disguise: merge partial results, combine filters, reduce collections, or compute values in parallel. Abstract algebra gives those operations precise names and laws, which makes it easier to design reusable code and reason about whether regrouping or parallel execution is safe. This article introduces semigroups and monoids through C# examples. The point is not to decorate ordinary code with mathematical vocabulary; it is to make composition rules explicit enough that the compiler and your teammates can see them. Many of us studied at technical universities and took a long list of mathematics courses while wondering why we needed them. Algebra may have been one of those courses. I do not mean a school textbook packed with tedious exercises about polynomials and equations. Abstract algebra is a difficult, expansive subject with a steep learning curve, but it is also fascinating. Its central objects of study are algebraic structures, which you can build almost anywhere and from almost anything. They can also inspire new approaches to writing code. Before we get there, let us take a short algebraic detour. Semigroups, Monoids, and Their Laws We will barely scratch the surface of abstract algebra. We will cover only the basic axioms and definitions needed to understand what is going on. There will not even be any theorems or proofs. Let us begin with an arbitrary set X , assuming familiarity with sets and mappings. If we take a mapping ∘ : X × X → X together with our set, we get an algebraic structure. In other words, an algebraic structure is a pair ( X , ∘ ) consisting of a set and a closed binary operation. The integers under addition, ( Z , + ) , are one example. This is where the operations become important: they determine the structure and behavior of the elements. Arbitrary functions are not useful enough, so we require them to have certain properties. Put differently, the operation must satisfy a set of axioms.