amonoid 0.1.2

A general-purpose monoid library
Documentation
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ffi::OsString;
use std::hash::Hash;

/// A [monoid](https://en.wikipedia.org/wiki/Monoid).
pub trait Monoid: Sized {
	/// The identity element for [`combine`](Self::combine).
	fn ident() -> Self;

	/// Combine an element with another element.
	/// This must obey
	/// - the left and right identity laws, that is `combine(ident(), x) == x` and `combine(x, ident()) == x` for all `x`.
	/// - the associative law, that is `combine(combine(a, b), c) == combine(a, combine(b, c))` for all `a, b, c`.
	fn combine(self, rhs: Self) -> Self;

	/// Like [`combine`](Self::combine), but assigns the result to `self`.
	///
	/// The default impl uses [`std::mem::replace`] with [`Self::ident`].
	fn combine_assign(&mut self, rhs: Self) {
		*self = std::mem::replace(self, Self::ident()).combine(rhs);
	}

	/// Like [`combine`](Self::combine), but assigns the result to `rhs`.
	///
	/// The default impl uses [`std::mem::replace`] with [`Self::ident`].
	fn combine_assign_to(self, rhs: &mut Self) {
		*rhs = self.combine(std::mem::replace(rhs, Self::ident()));
	}

	/// An overridable method to provide some optimization based on the fact that [`combine`](Self::combine) is associative.
	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.reduce(Self::combine).unwrap_or_else(Self::ident)
	}

	/// Like [`combine_iter`](Self::combine_iter), but assigns the result to `self`.
	fn combine_iter_assign<I: Iterator<Item = Self>>(&mut self, iter: I) {
		self.combine_assign(Self::combine_iter(iter))
	}
}

/// The unit type (type with one value) is a monoid, known as the [trivial], or [zero], monoid.
///
/// [trivial]: https://en.wikipedia.org/wiki/Trivial_monoid
/// [zero]: https://en.wikipedia.org/wiki/Initial_and_terminal_objects
impl Monoid for () {
	#[inline]
	fn ident() {}

	#[inline]
	fn combine(self, (): Self) {}

	#[inline]
	fn combine_assign(&mut self, (): Self) {}

	#[inline]
	fn combine_assign_to(self, (): &mut Self) {}

	#[inline]
	fn combine_iter<I: Iterator<Item = Self>>(_iter: I) {}

	#[inline]
	fn combine_iter_assign<I: Iterator<Item = Self>>(&mut self, _iter: I) {}
}

/// A tuple of two monoids is a monoid (with the operation acting componentwise), known as the [product] monoid.
///
/// [product]: https://en.wikipedia.org/wiki/Direct_product
impl<M1: Monoid, M2: Monoid> Monoid for (M1, M2) {
	#[inline]
	fn ident() -> Self {
		(M1::ident(), M2::ident())
	}

	#[inline]
	fn combine(self, rhs: Self) -> Self {
		(self.0.combine(rhs.0), self.1.combine(rhs.1))
	}

	#[inline]
	fn combine_assign(&mut self, rhs: Self) {
		self.0.combine_assign(rhs.0);
		self.1.combine_assign(rhs.1);
	}

	fn combine_assign_to(self, rhs: &mut Self) {
		self.0.combine_assign_to(&mut rhs.0);
		self.1.combine_assign_to(&mut rhs.1);
	}
}

/// The opposite monoid ([wiki](https://en.wikipedia.org/wiki/Monoid#Examples)), where `combine(a, b) = M::combine(b, a)`.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Opposite<M: Monoid>(pub M);

impl<M: Monoid> Monoid for Opposite<M> {
	fn ident() -> Self {
		Self(M::ident())
	}

	fn combine(self, rhs: Self) -> Self {
		Self(M::combine(rhs.0, self.0))
	}

	fn combine_assign(&mut self, rhs: Self) {
		M::combine_assign_to(rhs.0, &mut self.0);
	}

	fn combine_assign_to(self, rhs: &mut Self) {
		rhs.0.combine_assign(self.0);
	}

	// TODO: if specialization ever becomes stable, use it here to specialize `combine_iter` on `DoubleEndedIterator`.
}

/// An `Option<impl Monoid>` is also a monoid with `None` as the identity.
///
/// Actually, the inner type wouldn't even need to be a monoid
/// (since the `Option` provides the identity element, so the inner type would only need to be a [semigroup]),
/// but this crate is strictly about monoids, so it lacks a `Semigroup` trait.
/// Thus, the impl is a bit more restrictive than it would theoretically need to be.
///
/// [semigroup]: https://en.wikipedia.org/wiki/Semigroup
impl<M: Monoid> Monoid for Option<M> {
	#[inline]
	fn ident() -> Self {
		None
	}

	fn combine(self, rhs: Self) -> Self {
		self.zip(rhs).map(|(l, r)| l.combine(r))
	}

	fn combine_assign(&mut self, rhs: Self) {
		if let Some(rhs) = rhs {
			match self {
				None => *self = Some(rhs),
				Some(lhs) => lhs.combine_assign(rhs),
			}
		}
	}

	fn combine_assign_to(self, rhs: &mut Self) {
		if let Some(lhs) = self {
			match rhs {
				None => *rhs = Some(lhs),
				Some(rhs) => lhs.combine_assign_to(rhs),
			}
		}
	}

	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.flatten().reduce(M::combine)
	}
}

#[cfg(feature = "syn")]
/// [`syn::Error`] represents a non-empty list of [`compile_error!`] statements
/// and [`syn::Error::combine`] acts as concatenation.
/// This makes `syn::Error` into a semigroup
/// and `Option<syn::Error>` thus into a monoid,
/// as described [here](#impl-Monoid-for-Option<M>).
impl Monoid for Option<syn::Error> {
	#[inline]
	fn ident() -> Self {
		None
	}

	fn combine(self, rhs: Self) -> Self {
		self.zip(rhs).map(|(mut l, r)| {
			l.combine(r);
			l
		})
	}

	fn combine_assign(&mut self, rhs: Self) {
		if let Some(rhs) = rhs {
			match self {
				None => *self = Some(rhs),
				Some(lhs) => lhs.combine(rhs),
			}
		}
	}

	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.flatten().reduce(|mut l, r| {
			l.combine(r);
			l
		})
	}
}

/// The monoid of lists of `T` with concatenation as the operation,
/// also known as the [free monoid] on `T`.
///
/// [free monoid]: https://en.wikipedia.org/wiki/Free_monoid
impl<T> Monoid for Vec<T> {
	#[inline]
	fn ident() -> Self {
		Vec::new()
	}

	#[inline]
	fn combine(mut self, mut rhs: Self) -> Self {
		self.append(&mut rhs);
		self
	}

	#[inline]
	fn combine_assign(&mut self, mut rhs: Self) {
		self.append(&mut rhs);
	}

	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.flatten().collect()
	}

	fn combine_iter_assign<I: Iterator<Item = Self>>(&mut self, iter: I) {
		self.extend(iter.flatten());
	}
}

/// `String` is just a different encoding of `Vec<char>`
/// (see [`impl Monoid for Vec<T>`](Monoid#impl-Monoid-for-Vec<T>) for details).
impl Monoid for String {
	#[inline]
	fn ident() -> Self {
		String::new()
	}

	#[inline]
	fn combine(self, rhs: Self) -> Self {
		self + &rhs
	}

	#[inline]
	fn combine_assign(&mut self, rhs: Self) {
		self.push_str(&rhs);
	}

	#[inline]
	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.collect()
	}

	#[inline]
	fn combine_iter_assign<I: Iterator<Item = Self>>(&mut self, iter: I) {
		self.extend(iter);
	}
}

/// `OsString` is just a different encoding of `Vec<Something>` (What `Something` is depends on the OS)
/// (see [`impl Monoid for Vec<T>`](Monoid#impl-Monoid-for-Vec<T>) for details).
impl Monoid for OsString {
	#[inline]
	fn ident() -> Self {
		OsString::new()
	}

	#[inline]
	fn combine(mut self, rhs: Self) -> Self {
		self.push(rhs);
		self
	}

	#[inline]
	fn combine_assign(&mut self, rhs: Self) {
		self.push(rhs);
	}

	#[inline]
	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.collect()
	}

	#[inline]
	fn combine_iter_assign<I: Iterator<Item = Self>>(&mut self, iter: I) {
		self.extend(iter);
	}
}

/// Finite sets with elements of type `T` form a monoid under set union.
impl<T: Hash + Eq> Monoid for HashSet<T> {
	#[inline]
	fn ident() -> Self {
		HashSet::new()
	}

	#[inline]
	fn combine(mut self, rhs: Self) -> Self {
		self.extend(rhs);
		self
	}

	#[inline]
	fn combine_assign(&mut self, rhs: Self) {
		self.extend(rhs);
	}

	// note: `Self::combine` is commutative.
	#[inline]
	fn combine_assign_to(self, rhs: &mut Self) {
		rhs.extend(self);
	}

	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.flatten().collect()
	}

	fn combine_iter_assign<I: Iterator<Item = Self>>(&mut self, iter: I) {
		self.extend(iter.flatten())
	}
}

/// Finite sets with elements of type `T` form a monoid under set union.
impl<T: Ord> Monoid for BTreeSet<T> {
	#[inline]
	fn ident() -> Self {
		BTreeSet::new()
	}

	#[inline]
	fn combine(mut self, mut rhs: Self) -> Self {
		self.append(&mut rhs);
		self
	}

	#[inline]
	fn combine_assign(&mut self, mut rhs: Self) {
		self.append(&mut rhs);
	}

	// note: `Self::combine` is commutative.
	#[inline]
	fn combine_assign_to(mut self, rhs: &mut Self) {
		rhs.append(&mut self);
	}

	fn combine_iter<I: Iterator<Item = Self>>(iter: I) -> Self {
		iter.flatten().collect()
	}

	fn combine_iter_assign<I: Iterator<Item = Self>>(&mut self, iter: I) {
		self.extend(iter.flatten())
	}
}

/// Partial functions from any set to a monoid form a monoid
/// under union of domains and (if needed) combination of function values.
impl<K: Hash + Eq, M: Monoid> Monoid for HashMap<K, M> {
	#[inline]
	fn ident() -> Self {
		HashMap::new()
	}

	/// Use with caution; This might not be a very efficient operation.
	fn combine(mut self, rhs: Self) -> Self {
		self.combine_assign(rhs);
		self
	}

	/// Use with caution; This might not be a very efficient operation.
	fn combine_assign(&mut self, rhs: Self) {
		use std::collections::hash_map::Entry;

		for (k, vr) in rhs {
			match self.entry(k) {
				Entry::Occupied(e) => {
					let (k, vl) = e.remove_entry();
					self.insert(k, vl.combine(vr));
				}
				Entry::Vacant(e) => {
					e.insert(vr);
				}
			}
		}
	}

	/// Use with caution; This might not be a very efficient operation.
	fn combine_assign_to(self, rhs: &mut Self) {
		use std::collections::hash_map::Entry;

		for (k, vl) in self {
			match rhs.entry(k) {
				Entry::Occupied(e) => {
					let (k, vr) = e.remove_entry();
					rhs.insert(k, vl.combine(vr));
				}
				Entry::Vacant(e) => {
					e.insert(vl);
				}
			}
		}
	}
}

/// Partial functions from any set to a monoid form a monoid
/// under union of domains and (if needed) combination of function values.
impl<K: Ord, M: Monoid> Monoid for BTreeMap<K, M> {
	#[inline]
	fn ident() -> Self {
		BTreeMap::new()
	}

	/// Use with caution; This might not be a very efficient operation.
	fn combine(mut self, rhs: Self) -> Self {
		self.combine_assign(rhs);
		self
	}

	/// Use with caution; This might not be a very efficient operation.
	fn combine_assign(&mut self, rhs: Self) {
		use std::collections::btree_map::Entry;

		for (k, vr) in rhs {
			match self.entry(k) {
				Entry::Occupied(e) => {
					let (k, vl) = e.remove_entry();
					self.insert(k, vl.combine(vr));
				}
				Entry::Vacant(e) => {
					e.insert(vr);
				}
			}
		}
	}

	/// Use with caution; This might not be a very efficient operation.
	fn combine_assign_to(self, rhs: &mut Self) {
		use std::collections::btree_map::Entry;

		for (k, vl) in self {
			match rhs.entry(k) {
				Entry::Occupied(e) => {
					let (k, vr) = e.remove_entry();
					rhs.insert(k, vl.combine(vr));
				}
				Entry::Vacant(e) => {
					e.insert(vl);
				}
			}
		}
	}
}

/// Functions `T -> T` are monoids under composition.
impl<'a, T: 'a> Monoid for Box<dyn 'a + FnMut(T) -> T> {
	fn ident() -> Self {
		Box::new(std::convert::identity)
	}

	fn combine(mut self, mut rhs: Self) -> Self {
		Box::new(move |t| (*self)((*rhs)(t)))
	}
}
/// Functions `T -> T` are monoids under composition.
impl<'a, T: 'a> Monoid for Box<dyn 'a + Fn(T) -> T> {
	fn ident() -> Self {
		Box::new(std::convert::identity)
	}

	fn combine(self, rhs: Self) -> Self {
		Box::new(move |t| (*self)((*rhs)(t)))
	}
}