Created
January 11, 2014 07:25
-
-
Save pzol/8368103 to your computer and use it in GitHub Desktop.
pointer fun with lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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