Another kind of fold visitor
I'd like a visitor to "thread" an accumulator through a data type. If I had to write this visitor by hand, that would be something like:
type expr_node =
| EConst
| EAdd of expr * expr
class ['self] visitor = object (self : 'self)
inherit [_] visitor_for_basic_types
method visit_EConst _env acc = acc
method visit_EAdd env acc c0 c1 =
let acc = self#visit_expr env acc c0 in
let acc = self#visit_expr env acc c1 in
acc
method visit_expr env acc this =
match this with
| EConst c0 -> self#visit_EConst env acc c0
| EAdd (c0, c1) -> self#visit_EAdd env acc c0 c1
end
You can see in visit_EAdd
that the accumulator acc
is threaded through first a call to visit_expr c0
then through visit_expr c1
.
I usually achieve this with an iter visitor containing a mutable variable but there's some boilerplate involved to mutate the variable at the end of each method. Is there a better way? Would it be possible to have a dedicated visitor for this case?