I was trying to translate the following Haskell code to C++:
data List t = Nil | Cons t (List t)
The straightforward translation of the algebraic data type to the stateless Visitor pattern yields the following Java code
interface List<T> {
<R> R accept(ListVisitor<T,R> v);
}
interface ListVisitor<T,R> {
R visitNil();
R visitCons(T head, List<T> tail);
}
class Nil<T> implements List<T> {
@Override
public <R> R accept(ListVisitor<T,R> v) {
return v.visitNil();
}
}
class Cons<T> implements List<T> {
public final T head;
public final List<T> tail;
public Cons(T head, List<T> tail) {
this.head = head;
this.tail = tail;
}
@Override
public <R> R accept(ListVisitor<T,R> v) {
return v.visitCons(head, tail);
}
}
The following is the C++ code I have so far:
template<class T> class List;
template<class T, class R> class ListVisitor {
virtual R visitNil() = 0;
virtual R visitCons(T head, List<T> tail) = 0;
};
template<class T> class List {
template<class R> virtual R accept(ListVisitor<T,R> v) = 0;
};
Note that the Java version uses a virtual generic function accept
. When I translate it to C++, I end up with a virtual template function, which is not allowed by C++.
Is there a solution to it other than making accept
return void
and require visitors to be stateful?
Update: As requested, here are some examples of how the interfaces could be used (modulo smart pointers and possible compile errors):
template<class T> struct LengthVisitor : ListVisitor<T, int> {
bool visitNil() { return 0; }
bool visitCons(const T&, const List<T> &tail) { return 1 + tail.accept(*this); }
};
template<class T> struct ConcatVisitor : ListVisitor<T, const List<T> *> {
const List<T> *right;
ConcatVisitor(const List<T> *right) : right(right) {}
List<T> * visitNil() { return right; }
List<T> * visitCons(const T &head, const List<T> & tail) {
return new Cons(head, tail.accept(*this));
}
};
Another example, a higher-level function fold
, in Java, can be found here: http://hpaste.org/54650
visitCons
andaccept
methods also need to take a pointer to those abstract classes, rather than a value, so why not stateful? – Krissieconst &
. Alf, do you mean one should be happy usingvoid
and mutable visitors? – Moulden