1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! # Semigroup and Monoid
//!
//! Algebraic structures for *combinable* values. A [`Semigroup`](crate::monoid::Semigroup) has an
//! associative binary operation [`combine`](crate::monoid::Semigroup::combine) (Haskell's
//! `<>` / `mappend`); a [`Monoid`](crate::monoid::Monoid) additionally has an identity element
//! [`empty`](crate::monoid::Monoid::empty) (Haskell's `mempty`).
//!
//! These power the [`WriterT`](crate::transformers::writer) transformer, whose
//! log type must accumulate monoidally: `tell` appends with `combine`, and
//! `pure` starts the log at `empty`.
//!
//! ## Laws
//!
//! `Semigroup` — **associativity**:
//! ```text
//! a.combine(b).combine(c) == a.combine(b.combine(c))
//! ```
//! `Monoid` — **left and right identity**:
//! ```text
//! Monoid::empty().combine(x) == x
//! x.combine(Monoid::empty()) == x
//! ```
//!
//! ## Provided instances
//! - `()` — the trivial monoid (one element, the no-op log).
//! - `String` — concatenation, identity is `""`.
//! - `Vec<T>` — concatenation, identity is `[]`.
//!
//! ```
//! use monadify::monoid::{Semigroup, Monoid};
//!
//! assert_eq!("foo".to_string().combine("bar".to_string()), "foobar");
//! assert_eq!(vec![1, 2].combine(vec![3]), vec![1, 2, 3]);
//! assert_eq!(<String as Monoid>::empty().combine("x".to_string()), "x");
//! ```
/// A type with an associative binary operation, [`combine`](Self::combine).
///
/// Analogous to Haskell's `Semigroup` (`<>`). Implementations must be
/// **associative**: `a.combine(b).combine(c) == a.combine(b.combine(c))`.
/// A [`Semigroup`] with an identity element, [`empty`](Self::empty).
///
/// Analogous to Haskell's `Monoid` (`mempty`). The identity must satisfy
/// `empty().combine(x) == x` and `x.combine(empty()) == x`.
// --- Trivial monoid: () ---
// --- String under concatenation ---
// --- Vec<T> under concatenation ---