Skip to content

Instantly share code, notes, and snippets.

@rjwebb
Created April 11, 2017 22:41
Show Gist options
  • Save rjwebb/24fe13b3b1102baddd5dce7984e40acb to your computer and use it in GitHub Desktop.
Save rjwebb/24fe13b3b1102baddd5dce7984e40acb to your computer and use it in GitHub Desktop.

Revisions

  1. rjwebb created this gist Apr 11, 2017.
    60 changes: 60 additions & 0 deletions linked_list.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    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);
    }