Skip to content

Monoids & Semigroups

johnmcclean-aol edited this page Nov 22, 2016 · 2 revisions

cyclops-react defines interfaces for Monoids and Semigroups.

Semigroup (combines things of the same type)

A semigroup is an (associative) binary operation for combining values. Implementations should obey associativity laws. Or in plain English it is an interface that extends BinaryOperator (which itself is BiFunction for values of the same type). It should not matter in which order you pass the parameters to the BiFunction.

Semigroups

The Semigroups class defines a large number of Semigroups including int multiplication which looks like this

static Semigroup<Integer> intMult = (a, b) -> a * b;

Semigroups are very useful for folding or reducing data structures such as Streams (in fact reduce in java.util.stream.Stream accepts a BinaryOperator and an 'identity' value - more of which to follow), but they can be used all over the place - for example when zipping sequential structures or combining values.

Monoid (combines stuff, but defines an identity value).

An identity value is one that when applied with any given value to a combining function (semigroup) results in the other parameter being returned. For example the identity value of integer multiplication is 1 (1*2 results in 2), the identity value for Integer addition is 0 (0+5 results in 5).

The Monoid interface extends Semigroup but adds an additional method to get the identity or zero value.

Monoids

The Monoids class defines a large number of Monoids including int multiplication which looks like this

static Monoid<Integer> intMult =  Monoid.of(1, Semigroups.intMult);

The definition of a Monoid fits the interface used for folding / reduction in sequential data-structures such as Streams perfectly, and cyclops-react types will accept a Monoid object there.

Clone this wiki locally