Skip to content

Instantly share code, notes, and snippets.

@anka-213
Forked from anonymous/playground.rs
Last active April 13, 2016 13:07
Show Gist options
  • Save anka-213/a9b294f7183be2f0b59f081c82b8373e to your computer and use it in GitHub Desktop.
Save anka-213/a9b294f7183be2f0b59f081c82b8373e to your computer and use it in GitHub Desktop.
Using enum
use std::iter::FromIterator;
enum List { Nil, Cons{value: i32, next: Box<List>}}
fn main() {
let v = vec![1, 5, 3, 8, 12, 56, 1230, 2, 1];
//let root: List = v.iter().cloned().collect();
let root = List::from_iter(v);
println!("root: {}",
root.to_string());
}
impl Into<Option<(i32, Box<List>)>> for List {
fn into(self) -> Option<(i32, Box<List>)> {
match self { List::Nil => None, List::Cons{ value, next} => Some((value, next)) }
}
}
impl<'a> FromIterator<&'a i32> for List {
fn from_iter<I: IntoIterator<Item = &'a i32>>(iterator: I) -> Self {
iterator.into_iter().cloned().collect()
}}
impl FromIterator<i32> for List {
fn from_iter<I: IntoIterator<Item = i32>>(iterator: I) -> Self {
let mut root: List = List::Nil;
let mut prev: *mut List = &mut root;
for i in iterator {
let curr = List::Cons{
value: i,
next: Box::new(List::Nil),
};
unsafe {
(*prev) = curr;
if let &mut List::Cons{ ref mut next, ..} = &mut *prev {
prev = next.as_mut();
}
}
}
root
}
}
struct ListIter<'a> (&'a List);
impl<'a> Iterator for ListIter<'a> {
type Item = i32;
fn next(&mut self) -> Option<i32> {
if let List::Cons{value,ref next} = *self.0 {
self.0 = &*next;
Some(value)
} else {
None
}
}
}
impl<'a> IntoIterator for &'a List {
type Item = i32;
type IntoIter = ListIter<'a>;
fn into_iter(self) -> Self::IntoIter {
ListIter(self)
}
}
impl std::fmt::Display for List {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let mut first = true;
try!(write!(fmt, "["));
for value in self {
if !first {
try!(write!(fmt, ", "));
}
first = false;
try!(write!(fmt, "{}", value));
}
try!(write!(fmt, "]"));
Ok(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment