cross: list: implement a Visit trait.

it can't do much yet because the immutable-ness, but i can fix that.
This commit is contained in:
2022-08-18 02:32:52 -07:00
parent 5cc1c310b5
commit f2b23ace17

View File

@@ -162,6 +162,34 @@ where
}
}
pub trait Visitor<E> {
fn visit(&self, v: E);
}
pub struct VisitOp<V>(V);
impl<V, Next> FoldOp<(), Next> for VisitOp<V>
where
V: Visitor<Next>
{
type Output = ();
fn feed(&self, _prev: (), next: Next) {
self.0.visit(next)
}
}
/// invokes the Visitor `V` on every element of the list.
pub trait Visit<V> {
fn visit(self, v: V);
}
impl<V, L> Visit<V> for L
where
L: Fold<VisitOp<V>, (), Output=()>
{
fn visit(self, v: V) {
self.fold(VisitOp(v), ())
}
}
pub struct ReverseOp;
impl<Prev, Next> FoldOp<Prev, Next> for ReverseOp {
@@ -445,6 +473,20 @@ mod test {
assert!(list == list); // just check that it wasn't consumed
}
struct NoopVisitor;
impl<V> Visitor<V> for NoopVisitor {
fn visit(&self, _e: V) {}
}
#[test]
fn visit_noop() {
let list = (3f32, NotCopy(4i32), 5u32).into_list();
list.visit(NoopVisitor);
let list = &(3f32, NotCopy(4i32), 5u32).into_list();
list.visit(NoopVisitor);
}
#[test]
fn sum() {
let list = (3i32, 4i32, 5i32).into_list();