A monoid: a set of values with an associative binary operation and identity element.
A Monoid captures a fundamental algebraic structure consisting of:
- A type
Trepresenting the set of values - A binary operation combine that combines two values of type
T - An identity element empty that doesn't change the result when combined
Monoid laws (assumed but not enforced):
- Closure: For any
a, b : T,combine(a, b) : T(combining two values produces another value of the same type) - Associativity:
combine(combine(a, b), c) == combine(a, combine(b, c))(the order of grouping doesn't matter, only the order of application) - Identity:
combine(empty, a) == aandcombine(a, empty) == a(the empty element doesn't change anything when combined)
These laws are assumed to be satisfied by all implementations.
Common examples:
- Integers with addition: empty = 0, combine = (a, b) => a + b
- Integers with multiplication: empty = 1, combine = (a, b) => a * b
- Strings with concatenation: empty = "", combine = (a, b) => a + b
- Lists with concatenation: empty = [], combine = (a, b) => a + b
- Booleans (logical OR): empty = false, combine = (a, b) => a || b
- Booleans (logical AND): empty = true, combine = (a, b) => a && b
- Any type with min/max: empty = max/min value, combine = (a, b) => min/max(a, b)
Use cases:
- Aggregation and reduction: Combine multiple values into a single result
- Parallel/distributed computation: Combine partial results from independent computations
- Accumulation: Build up a value by repeatedly combining increments
- Defaults and folding: Safely reduce collections to a single value with predictable behavior
Example - implementing a sum monoid:
class SumMonoid implements Monoid<int> {
const SumMonoid();
@override
int get empty => 0;
@override
int combine(int a, int b) => a + b;
}
// Usage
final sum = SumMonoid();
final result = [1, 2, 3, 4].fold(sum.empty, sum.combine); // 10
assert(result == 10);
Example - implementing a string concatenation monoid:
class StringMonoid implements Monoid<String> {
const StringMonoid();
@override
String get empty => '';
@override
String combine(String a, String b) => a + b;
}
// Usage
final str = StringMonoid();
final words = ['Hello', ' ', 'World'];
final result = words.fold(str.empty, str.combine); // 'Hello World'
- Annotations
-
- @experimental
Properties
- empty → T
-
The identity element of this monoid.
no setter
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
combine(
T a, T b) → T -
Combines two values of type
Tinto a single value. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited