public
anonymous / flist.rs
Created

  • Download Gist
flist.rs
Rust
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
#[deriving(Clone)]
enum List<T> {
Empty,
Cons(T, ~List<T>)
}
impl<T: Eq + Clone> List <T> {
fn map(&self, f: &fn(T)->T)->List<T>{
match *self {
Empty => Empty,
Cons(ref x, ref xs) => Cons(f(x.clone()),~xs.map(f))
}
}
fn foldl<U>(&self,acc: U, f: &fn(U,T) -> U) -> U{
match *self {
Empty => acc,
Cons(ref x, ref xs) => xs.foldl(f(acc,x.clone()),f)
}
}
fn fst(&self)-> T{
match *self {
Cons(ref x,_) => x.clone(),
Empty => fail!(~"You called 'fst' on an empty list!")
}
}
fn lst(&self)->T{
match *self {
Cons(ref x, ~Empty) => x.clone(),
Cons(_,ref xs) => xs.lst(),
Empty => fail!(~"You called 'lst' on an empty list!")
}
}
fn singleton(elem: T) -> List<T>{
Cons(elem,~Empty)
}
fn prepend(&self,elem: T) -> List<T> {
match *self {
Empty => Cons(elem,~Empty),
Cons(_,_) => Cons(elem,~(self.clone()))
}
}
fn push(&self, elem: T) -> List<T> {
match *self {
Empty => List::singleton(elem),
Cons(ref x,~Empty) => Cons(x.clone(),~List::singleton(elem)),
Cons(ref x,ref xs) => Cons(x.clone(),~xs.push(elem))
}
}
fn elem_at(&self, n: int) -> T {
match *self {
Cons(ref x,_) if n == 0 => x.clone(),
Cons(_,ref xs) if n > 0 => xs.elem_at(n-1),
_=> fail!(~"out of bounds")
}
}
fn contains(&self, elem: T) -> bool {
match *self {
Empty => false,
Cons(ref x,_) if *x == elem => true,
Cons(_,ref xs)=> xs.contains(elem)
}
}
fn length(&self) -> uint{
match *self {
Empty => 0,
Cons(_, ref xs) => 1 + xs.length()
}
}
}
fn main() {
let l = Empty.push(1)
.push(2)
.push(3)
.prepend(0);
 
let sum = l.foldl(0,|a, x| a + x );
let twice = l.map(|x| x * 2 );
 
printfln!(l); // Cons(0, ~Cons(1, ~Cons(2, ~Cons(3, ~Empty))))
printfln!(l.contains(42)); // false
printfln!(l.contains(3)); // true
printfln!(l.elem_at(3)); // 3
printfln!(l.length()); // 4
printfln!(l.fst()); // 0
printfln!(l.lst()); // 3
printfln!(sum); // 6
printfln!(twice); // Cons(0, ~Cons(2, ~Cons(4, ~Cons(6, ~Empty))))
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.