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
use super::*;
pub type FreeGroup<C> = MonoidalString<FreeInv<C>,InvRule>;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum FreeInv<T:Eq> {
Id(T),
Inv(T)
}
impl<T:Eq> From<T> for FreeInv<T> {
fn from(t:T) -> Self { FreeInv::Id(t) }
}
impl<T:Eq> AsRef<T> for FreeInv<T> {
fn as_ref(&self) -> &T {
match self {
FreeInv::Id(ref x) => x,
FreeInv::Inv(ref x) => x
}
}
}
impl<T:Eq> AsMut<T> for FreeInv<T> {
fn as_mut(&mut self) -> &mut T {
match self {
FreeInv::Id(ref mut x) => x,
FreeInv::Inv(ref mut x) => x
}
}
}
impl<T:Eq> PartialEq<T> for FreeInv<T> {
fn eq(&self, rhs:&T) -> bool {
match self {
FreeInv::Id(x) => x==rhs,
FreeInv::Inv(_) => false
}
}
}
impl<T:Eq+Display> Display for FreeInv<T> {
fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
match self {
Self::Id(x) => write!(f, "{}", x),
Self::Inv(x) => write!(f, "{}⁻¹", x),
}
}
}
impl<T:Eq> FreeInv<T> {
pub fn is_inv(&self) -> bool {
match self { Self::Inv(_) => true, _ => false }
}
pub fn is_id(&self) -> bool {
match self { Self::Id(_) => true, _ => false }
}
fn are_inverses(&self, rhs:&Self) -> bool {
self.as_ref()==rhs.as_ref() && self.is_inv()^rhs.is_inv()
}
}
pub struct InvRule;
impl<T:Eq> AssociativeMonoidRule<FreeInv<T>> for InvRule {}
impl<T:Eq> MonoidRule<FreeInv<T>> for InvRule {
fn apply(mut string: Vec<FreeInv<T>>, letter: FreeInv<T>) -> Vec<FreeInv<T>> {
if string.last().map_or(false, |last| letter.are_inverses(last)) {
string.pop();
} else {
string.push(letter);
}
string
}
}
impl<T:Eq> InvMonoidRule<FreeInv<T>> for InvRule {
fn invert(letter: FreeInv<T>) -> FreeInv<T> { letter.inv() }
}
impl<T:Eq> Inv for FreeInv<T> {
type Output = Self;
fn inv(self) -> Self {
match self {
Self::Id(x) => Self::Inv(x),
Self::Inv(x) => Self::Id(x)
}
}
}
impl<T:Eq> Mul for FreeInv<T> {
type Output = FreeGroup<T>;
fn mul(self, rhs:Self) -> FreeGroup<T> { FreeGroup::from(self) * rhs }
}
impl<T:Eq> Div for FreeInv<T> {
type Output = FreeGroup<T>;
fn div(self, rhs:Self) -> FreeGroup<T> { self * rhs.inv() }
}
impl<T:Eq> Mul<FreeGroup<T>> for FreeInv<T> {
type Output = FreeGroup<T>;
fn mul(self, rhs:FreeGroup<T>) -> FreeGroup<T> { FreeGroup::from(self) * rhs }
}
impl<T:Eq> Div<FreeGroup<T>> for FreeInv<T> {
type Output = FreeGroup<T>;
fn div(self, rhs:FreeGroup<T>) -> FreeGroup<T> { FreeGroup::from(self) / rhs }
}