Using monoids
Let's start by exploring monoids. In order to define a monoid, we must first understand what a semigroup is.
Note
The following examples can be found in src/m_clj/c6/
monoids.clj
of the book's source code.
A semigroup is an algebraic structure that supports an associative binary operation. A binary operation, say , is termed associative if the operation produces the same result as the operation . A monoid is in fact a semigroup with an additional property, as we will see ahead.
The mappend
function from the cats.core
namespace will associatively combine a number of instances of the same type and return a new instance of the given type. If we are dealing with strings or vectors, the mappend
operation is implemented by the standard concat
function. Thus, strings and vectors can be combined using the mappend
function, as shown here:
user> (cc/mappend "12" "34" "56") "123456" user> (cc/mappend [1 2] [3 4] [5 6]) [1 2 3 4 5 6...