Last active
January 3, 2016 07:19
-
-
Save darkone23/8428866 to your computer and use it in GitHub Desktop.
how do i link list
This file contains 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
use std::fmt::Default; | |
enum List<T> { | |
Cons(T, ~List<T>), | |
Nil | |
} | |
fn cons<T>(x: T, xs: List<T>) -> List<T> { | |
Cons(x, ~xs) | |
} | |
fn tail<'a, T>(xs: &'a List<T>) -> &'a List<T> { | |
match xs { | |
&Cons(_, ~ref ys) => ys, | |
&Nil => fail!("Cannot take the tail of an empty list") | |
} | |
} | |
fn print_list<T: Default>(xs: &List<T>) { | |
match (xs) { | |
&Nil => println!("End of list"), | |
&Cons(ref x, ~ref ys) => { | |
println!("Found cons cell: {}", *x); | |
print_list(ys) | |
} | |
} | |
} | |
fn main() { | |
let list = cons(1, cons(2, cons(3, Nil))); | |
print_list(&list); | |
let list_two = tail(&list); | |
print_list(list_two); | |
print_list(&list); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment