-
Notifications
You must be signed in to change notification settings - Fork 0
/
algebraic_lists.rs
50 lines (45 loc) · 1.01 KB
/
algebraic_lists.rs
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
#[derive(Debug, PartialEq, Eq)]
enum Cons<T: Clone> {
Cons(T, Box<Cons<T>>),
Null
}
impl<T: Clone> Cons<T> {
pub fn new(head: T, tail: Self) -> Self {
Cons::Cons(head, Box::new(tail))
}
pub fn to_vec(&self) -> Vec<T> {
match self {
&Cons::Null => vec![],
&Cons::Cons(ref head, ref tail) => {
let mut head = vec![head.clone()];
head.extend(tail.to_vec());
head
}
}
}
}
impl<T: Clone> Cons<T> {
pub fn from_iter<I>(it: I) -> Self
where I: IntoIterator<Item=T>
{
let mut v = vec![];
let mut c = Cons::Null;
for e in it {
v.push(e);
}
for e in v.iter().cloned().rev() {
c = Cons::new(e,c);
}
return c
}
pub fn filter<F>(&self, f: F) -> Self
where F: Fn(&T) -> bool
{
Cons::from_iter(self.to_vec().iter().cloned().filter(|e| f(e)))
}
pub fn map<F,S>(&self, f: F) -> Cons<S>
where F: Fn(T) -> S, S: Clone
{
Cons::from_iter(self.to_vec().iter().cloned().map(|e| f(e)))
}
}