Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
persistent stack
use std::sync::Arc;
struct List<T> {
head: Link<T>,
}
type Link<T> = Option<Arc<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
impl<T> List<T> {
fn new() -> Self {
List { head: None }
}
fn append(&self, elem: T) -> List<T> {
List {
head: Some(Arc::new(Node {
elem: elem,
next: self.head.clone(),
})),
}
}
fn tail(&self) -> List<T> {
List {
head: self.head.as_ref().and_then(|node| node.next.clone()),
}
}
fn head(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.elem)
}
fn iter(&self) -> Iter<'_, T> {
Iter {
next: self.head.as_ref().map(|node| &**node),
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.elem
})
}
}
#[test]
fn basics() {
let list = List::new();
assert_eq!(list.head(), None);
let list = list.append(1).append(2).append(3);
assert_eq!(list.head(), Some(&3));
let list = list.tail();
assert_eq!(list.head(), Some(&2));
let list = list.tail();
assert_eq!(list.head(), Some(&1));
let list = list.tail();
assert_eq!(list.head(), None);
let list = list.tail();
assert_eq!(list.head(), None);
}
#[test]
fn iter() {
let list = List::new().append(1).append(2).append(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), None);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment