use std::fmt::Debug;
#[derive(Debug)]
pub enum List<T> {
Cons(T, Box<List<T>>),
Nil,
}
impl<T: Debug> List<T> {
pub fn new() -> Self {
List::Nil
}
pub fn prepend(self, elem: T) -> List<T> {
List::Cons(elem, Box::new(self))
}
pub fn append(self, elem: T) -> List<T> {
match self {
List::Cons(_, _) => List::Cons(elem, Box::new(self)),
List::Nil => self.prepend(elem),
}
}
pub fn len(&self) -> u32 {
match *self {
List::Cons(_, ref tail) => 1 + tail.len(),
List::Nil => 0,
}
}
pub fn stringify(&self) -> String {
match *self {
List::Cons(ref head, ref tail) => format!("{:?},{}", *head, tail.stringify()),
List::Nil => format!("Nil"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let list = List::<u32>::new();
assert!(match list {
List::Cons(_, _) => false,
List::Nil => true,
});
let list = list.prepend(1);
let list = list.prepend(5);
assert_eq!(list.len(), 2, "list is {:?}", list);
assert_eq!(list.stringify(), "5,1,Nil", "expect {}.", list.stringify());
}
}