Skip to content

Instantly share code, notes, and snippets.

@pzol
Created January 11, 2014 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pzol/8368103 to your computer and use it in GitHub Desktop.
Save pzol/8368103 to your computer and use it in GitHub Desktop.
pointer fun with lists
#[allow(dead_code, dead_assignment, unused_variable)];
// recursive types
enum List<T> {
Cons(T, ~List<T>),
Empty
}
fn length<T>(xs: &List<T>) -> uint {
match *xs {
Empty => 0,
Cons(_, ref rest) => 1 + length(*rest)
}
}
fn prepend<'a, T>(xs: ~List<T>, value: T) -> List<T> {
Cons(value, xs)
}
// return a reference to the head value
fn head<'a, T>(xs: &'a List<T>) -> Option<&'a T> {
match *xs {
Cons(ref value, _) => Some(value),
_ => None
}
}
#[test]
fn test_length() {
let mut list: List<int> = Empty::<int>;
list = prepend(~list, 1);
list = prepend(~list, 2);
let list_len = length(&list);
assert_eq!(list_len, 2);
}
#[test]
fn test_head() {}
let h = head(&list);
assert_eq!(h, Some(&2));
let result: int = match h {
None => 0,
Some(value) => *value
};
println!("{}", result);
assert_eq!(result, 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment