Created
April 11, 2017 22:41
-
-
Save rjwebb/24fe13b3b1102baddd5dce7984e40acb to your computer and use it in GitHub Desktop.
Very basic linked list in Rust
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; | |
/* | |
Made this to experiment with making abstract data structures in Rust. | |
I'm not entirely convinced that it's necessary to use Box here... | |
*/ | |
fn flip(p: &Point) -> Point { | |
Point{ x: p.y, y: p.x } | |
} | |
fn map_ll<T, F>(list: &LinkedList<T>, func: F) -> LinkedList<T> where F: Fn(&T) -> T { | |
LinkedList { | |
head: func(&list.head), | |
tail: match list.tail { | |
Some(ref ll) => Some(Box::new(map_ll(&ll, func))), | |
None => None | |
} | |
} | |
} | |
struct Point { | |
x: i32, | |
y: i32, | |
} | |
impl fmt::Display for Point { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "(x: {}, y: {})", self.x, self.y) | |
} | |
} | |
struct LinkedList<T> { | |
head: T, | |
tail: Option<Box<LinkedList<T>>>, | |
} | |
impl <T: fmt::Display> fmt::Display for LinkedList<T> { | |
fn fmt(&self, f: &mut fmt:: Formatter) -> fmt::Result { | |
match self.tail { | |
Some(ref ll) => write!(f, "{} -> {}", self.head, ll), | |
None => write!(f, "{}", self.head), | |
} | |
} | |
} | |
fn main() { | |
let p = Point { x: 10, y: 20 }; | |
let p2 = Point { x: 30, y: 40 }; | |
let l = LinkedList { head: p, tail: Some(Box::new(LinkedList { head: p2, tail: None })) }; | |
let l2 = map_ll(&l, flip); | |
println!("linked list: {}", l); | |
println!("linked list (flipped): {}", l2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment