use crate::List::*;
enum List {
Cons(u32, Box<List>),
Nil,
}
impl List {
fn new() -> List {
Nil
}
fn prepend(self, elem: u32) -> List {
Cons(elem, Box::new(self))
}
fn len(&self) -> i32 {
fn get_len(tail: &List, _counter: i32) -> i32{
match tail{
Cons(_, tail) => get_len(tail, _counter+1),
Nil => _counter
}
}
get_len(self, 0)
}
fn stringify(&self) -> String {
fn get_stringfy(tail: &List, mut strif:Vec<String>) -> String{
match tail {
Cons(head, tail) => {
let dis_as = format!("{}", head);
strif.push(dis_as);
get_stringfy(tail, strif)
}
Nil => {
strif.push("Nil".to_string());
strif.join(", ")
}
}
}
get_stringfy(self, vec![])
}
fn stringify_2(&self) -> String {
fn get_stringfy_2(tail: &List, mut strif:String) -> String{
match tail{
Cons(head, tail) => {
let dis_as = format!("{}, ", head);
strif.push_str(&dis_as);
get_stringfy_2(tail, strif)
}
Nil => {
strif.push_str("Nil");
strif
}
}
}
get_stringfy_2(self, String::new())
}
}
fn main() {
let mut list = List::new();
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
println!("{}", list.stringify_2());
}
Comments
Post a Comment