Created
April 19, 2016 21:14
-
-
Save anonymous/fa3fa1d3b35316539ba6479c3a1e0a75 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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
//#![allow(dead_code)] | |
use std::iter::FromIterator; | |
// Example of linked lists -- Comes from stackoverflow | |
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 { // Can this be done without "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