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
use core::convert::Infallible;

/// A `Semigroup` is a type with an associative operation. In plain terms, this
/// means you can take two values of this type and add them together into a
/// different value of the same type. The most obvious example of this is
/// addition of numbers: `2 + 2 = 4`, another is string concatenation:
/// `"Hello " + "Joe" = "Hello Joe"`.
///
/// Semigroups must follow the law of associativity:
/// * `(x + y) + z = x + (y + z)`
///
/// A `Semigroup` differs from `std::ops::Add` in that `Add` can be defined
/// for any collection of types, eg. you could define `Add` for a type `A` which
/// takes a second argument of type `B` and returns a third type `C`, whereas a
/// `Semigroup` only deals with a single type `A`.
pub trait Semigroup {
    fn mappend(self, other: Self) -> Self;
}

#[cfg(feature = "std")]
impl<A> Semigroup for Vec<A> {
    fn mappend(mut self, other: Self) -> Self {
        self.extend(other);
        self
    }
}

#[cfg(feature = "std")]
impl Semigroup for String {
    fn mappend(self, other: Self) -> Self {
        self + &other
    }
}

impl Semigroup for () {
    fn mappend(self, _other: Self) -> Self {
        ()
    }
}

impl Semigroup for Infallible {
    fn mappend(self, _other: Self) -> Self {
        unreachable!()
    }
}

macro_rules! define_semigroup {
    ($type:ty) => {
        impl Semigroup for $type {
            fn mappend(self, other: Self) -> Self {
                self + other
            }
        }
    };
}

define_semigroup!(i8);
define_semigroup!(i16);
define_semigroup!(i32);
define_semigroup!(i64);
define_semigroup!(i128);
define_semigroup!(isize);
define_semigroup!(u8);
define_semigroup!(u16);
define_semigroup!(u32);
define_semigroup!(u64);
define_semigroup!(u128);
define_semigroup!(usize);