Skip to content

Instantly share code, notes, and snippets.

Created August 15, 2013 14:14
Show Gist options
  • Save anonymous/6241133 to your computer and use it in GitHub Desktop.
Save anonymous/6241133 to your computer and use it in GitHub Desktop.
#[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))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment