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
#![warn(missing_docs)]
#[cfg(feature = "with_serde")]
#[macro_use]
extern crate serde_derive;
use std::ops::Add;
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(feature = "with_serde", derive(Serialize, Deserialize))]
pub struct Nil;
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(feature = "with_serde", derive(Serialize, Deserialize))]
pub struct Cons<H, T>(pub H, pub T);
pub trait HList: Sized {
fn push<N>(self, item: N) -> Cons<N, Self> {
Cons(item, self)
}
}
impl HList for Nil {}
impl<H, T> HList for Cons<H, T> {}
#[allow(dead_code)]
pub enum Here {}
#[allow(dead_code)]
pub struct There<T>(std::marker::PhantomData<T>);
pub trait Find<T, I> {
fn get(&self) -> &T;
fn get_mut(&mut self) -> &mut T;
}
impl<T, Tail> Find<T, Here> for Cons<T, Tail> {
fn get(&self) -> &T {
&self.0
}
fn get_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<Head, T, Tail, TailIndex> Find<T, There<TailIndex>> for Cons<Head, Tail>
where Tail: Find<T, TailIndex> {
fn get(&self) -> &T {
self.1.get()
}
fn get_mut(&mut self) -> &mut T {
self.1.get_mut()
}
}
impl<RHS> Add<RHS> for Nil {
type Output = RHS;
fn add(self, rhs: RHS) -> RHS {
rhs
}
}
impl<H, T, RHS> Add<RHS> for Cons<H, T>
where T: Add<RHS> {
type Output = Cons<H, <T as Add<RHS>>::Output>;
fn add(self, rhs: RHS) -> Self::Output {
Cons(self.0, self.1 + rhs)
}
}
#[test]
fn test_get() {
let list = Nil.push(5i32).push("Foo");
let a: i32 = *list.get();
let b: &str = *list.get();
assert!(a == 5i32);
assert!(b == "Foo");
}
#[test]
fn test_get_mut() {
let mut list = Nil.push(5i32).push("Foo");
*list.get_mut() = 6i32;
*list.get_mut() = "Bar";
let a: i32 = *list.get();
let b: &str = *list.get();
assert!(a == 6i32);
assert!(b == "Bar");
}
#[test]
fn test_index_as_type_parameter() {
fn foo<I, L: Find<i32, I>>(list: &L) -> i32 {
*list.get()
}
let list = Nil.push("foo").push(5i32).push("bar");
assert!(foo(&list) == 5);
}
#[test]
fn test_hlist_addition() {
let list_1 = Nil.push(0i32);
let list_2 = Nil.push("Foo");
let list_3 = list_1 + list_2;
let a: i32 = *list_3.get();
let b: &str = *list_3.get();
assert!(a == 0i32);
assert!(b == "Foo");
}