Skip to content

Instantly share code, notes, and snippets.

@rjwebb
Created April 11, 2017 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjwebb/24fe13b3b1102baddd5dce7984e40acb to your computer and use it in GitHub Desktop.
Save rjwebb/24fe13b3b1102baddd5dce7984e40acb to your computer and use it in GitHub Desktop.
Very basic linked list in Rust
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