Skip to content

Commit 52524bf

Browse files
committed
Implemented Items<'a, T> for List<T>
1 parent 2b36276 commit 52524bf

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/libcollections/list.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,42 @@ pub enum List<T> {
1717
Nil,
1818
}
1919

20+
pub struct Items<'a, T> {
21+
priv head: &'a List<T>,
22+
priv next: Option<&'a @List<T>>
23+
}
24+
25+
impl<'a, T> Iterator<&'a T> for Items<'a, T> {
26+
fn next(&mut self) -> Option<&'a T> {
27+
match self.next {
28+
None => match *self.head {
29+
Nil => None,
30+
Cons(ref value, ref tail) => {
31+
self.next = Some(tail);
32+
Some(value)
33+
}
34+
},
35+
Some(next) => match **next {
36+
Nil => None,
37+
Cons(ref value, ref tail) => {
38+
self.next = Some(tail);
39+
Some(value)
40+
}
41+
}
42+
}
43+
}
44+
}
45+
46+
impl<T> List<T> {
47+
/// Returns a forward iterator
48+
pub fn iter<'a>(&'a self) -> Items<'a, T> {
49+
Items {
50+
head: self,
51+
next: None
52+
}
53+
}
54+
}
55+
2056
/**
2157
* Left fold
2258
*
@@ -181,6 +217,16 @@ mod tests {
181217

182218
use std::option;
183219

220+
#[test]
221+
fn test_iter() {
222+
let list = List::from_vec([0, 1, 2]);
223+
let mut iter = list.iter();
224+
assert_eq!(&0, iter.next().unwrap());
225+
assert_eq!(&1, iter.next().unwrap());
226+
assert_eq!(&2, iter.next().unwrap());
227+
assert_eq!(None, iter.next());
228+
}
229+
184230
#[test]
185231
fn test_is_empty() {
186232
let empty : @list::List<int> = @List::from_vec([]);

0 commit comments

Comments
 (0)