Lucas Stadler лет назад: 11
Родитель
Сommit
a223bfc55c
1 измененных файлов с 34 добавлено и 0 удалено
  1. 34 0
      rust/list.rs

+ 34 - 0
rust/list.rs

@ -0,0 +1,34 @@
1
#[deriving(Show)]
2
pub enum List<A> {
3
    Nil,
4
    Cons(A, Box<List<A>>)
5
}
6
7
// xs: doesn't work as a reference, probably as Box?
8
pub fn cons<A>(x: A, xs: List<A>) -> List<A> {
9
    match xs {
10
        Nil => Cons(x, box Nil),
11
        l => Cons(x, box l)
12
    }
13
}
14
15
pub fn first<A>(xs: &List<A>) -> Option<&A> {
16
    match xs {
17
        &Nil => None,
18
        &Cons(ref x, _) => Some(x)
19
    }
20
}
21
22
// nth
23
// map - does this make sense? (e.g. we probably don't want to copy everything.) should it be lazy?
24
//   fn map(..., &List<&A>) -> List<B> // or -> List<&B>?
25
// filter - we want references to the old values and keep the existing cons cells
26
// reduce
27
28
pub fn main() {
29
	let nil: &List<int> = &Nil;
30
	let ns:  &List<int> = &cons(1i, cons(2, cons(3, Nil)));
31
32
	println!("nil = {}, ns = {}", nil, ns);
33
	println!("first(nil) = {}, first(ns) = {}", first(nil), first(ns));
34
}