Skip to content

Instantly share code, notes, and snippets.

@dylanjw
Last active May 21, 2020 19:26
Show Gist options
  • Save dylanjw/49afe884270440c54e6eef7290f12d75 to your computer and use it in GitHub Desktop.
Save dylanjw/49afe884270440c54e6eef7290f12d75 to your computer and use it in GitHub Desktop.
Functional Data Structures ex 2.1
use std::rc::Rc;
#[derive(Debug)]
pub struct List<T> {
head: Link<T>,
}
type Link<T> = Option<Rc<Node<T>>>;
// Option because sometimes there is no Node.
// Nodes need to be wrapped in an RC because we need to
// allow multiple Links to own a single node.
#[derive(Debug)]
struct Node<T> {
elem: T,
next: Link<T>,
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn append(&self, elem: T) -> List<T> {
List { head: Some(Rc::new(Node {
elem: elem,
next: self.head.clone(),
}))}
}
}
fn create_range_list(n : i32) -> List<i32> {
let mut l : List<i32> = List::new();
for i in 0..n {
l = l.append(i);
}
l
}
fn main() {
let a = create_range_list(4);
let b = List { head: Some(Rc::clone(&a.head.unwrap())) };
let c = List { head: Some(Rc::clone(&b.head.unwrap())) };
let d = List { head: Some(Rc::clone(&c.head.unwrap())) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment