Skip to content

Commit

Permalink
Implemented Items<'a, T> for List<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
brunoabinader committed Feb 27, 2014
1 parent 2b36276 commit 52524bf
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/libcollections/list.rs
Expand Up @@ -17,6 +17,42 @@ pub enum List<T> {
Nil,
}

pub struct Items<'a, T> {
priv head: &'a List<T>,
priv next: Option<&'a @List<T>>
}

impl<'a, T> Iterator<&'a T> for Items<'a, T> {
fn next(&mut self) -> Option<&'a T> {
match self.next {
None => match *self.head {
Nil => None,
Cons(ref value, ref tail) => {
self.next = Some(tail);
Some(value)
}
},
Some(next) => match **next {
Nil => None,
Cons(ref value, ref tail) => {
self.next = Some(tail);
Some(value)
}
}
}
}
}

impl<T> List<T> {
/// Returns a forward iterator
pub fn iter<'a>(&'a self) -> Items<'a, T> {
Items {
head: self,
next: None
}
}
}

/**
* Left fold
*
Expand Down Expand Up @@ -181,6 +217,16 @@ mod tests {

use std::option;

#[test]
fn test_iter() {
let list = List::from_vec([0, 1, 2]);
let mut iter = list.iter();
assert_eq!(&0, iter.next().unwrap());
assert_eq!(&1, iter.next().unwrap());
assert_eq!(&2, iter.next().unwrap());
assert_eq!(None, iter.next());
}

#[test]
fn test_is_empty() {
let empty : @list::List<int> = @List::from_vec([]);
Expand Down

0 comments on commit 52524bf

Please sign in to comment.