You can now iterate a list
This commit is contained in:
parent
ea7ccfffb5
commit
e5e192a142
43
src/list.rs
43
src/list.rs
|
@ -14,4 +14,47 @@ impl<'a> List<'a> {
|
|||
.rev()
|
||||
.fold(Self::Nil, |list, next| Self::Cons(next, Box::new(list)))
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> Iter<'_, '_> {
|
||||
Iter(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Iter<'l, 'v>(&'l List<'v>);
|
||||
impl<'l, 'v> Iterator for Iter<'l, 'v> {
|
||||
type Item = &'l Value<'v>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self.0 {
|
||||
List::Cons(head, rest) => {
|
||||
self.0 = &**rest;
|
||||
Some(head)
|
||||
}
|
||||
List::Nil => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for List<'a> {
|
||||
type Item = Value<'a>;
|
||||
type IntoIter = IntoIter<'a>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
IntoIter(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct IntoIter<'a>(List<'a>);
|
||||
impl<'a> Iterator for IntoIter<'a> {
|
||||
type Item = Value<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match std::mem::take(&mut self.0) {
|
||||
List::Cons(first, mut rest) => {
|
||||
std::mem::swap(&mut self.0, rest.as_mut());
|
||||
Some(first)
|
||||
}
|
||||
List::Nil => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue