3 ms·
My C++ is rusty but you'd do it exactly like you do in ML. Something like: template<typename T> class List<T> { protected: List(); temp
by lmm 9y ago
My C++ is rusty but you'd do it exactly like you do in ML. Something like:
template<typename T> class List<T> {
protected:
List();
template<typename U> class Visitor<U> {
public:
U visitNil();
U visitCons(T current, U accumulator);
}
public:
virtual <U> U visit(Vistor<U> visitor);
}
template<typename T> class Nil<T> extends List<T> {
U visit(Visitor<U> visitor) = visitor.visitNil();
}
template<typename T> class Cons<T> extends List<T> {
private:
T head;
List<T> &tail;
public:
Cons(T head, List<T> &tail) {
this.head = head;
this.tail = tail;
}
U visit(Visitor<U> visitor) = visitor.visitCons(head, tail.visit(visitor));
}
- vbezhenar 9y agoThanks, that neat. But how would you build a list of arbitrary length and free it later? You'll use pointers, one way or another. The only way to avoid pointers I could imagine is to use stack with recursion, but that's completely crazy and limited programming style.