I like your animals especially your ducks in the UML diagrams :-D
I'm currently stuck with a problem at work trying to implement a visitor on an expression tree and then realizing I need to use a stack exactly as you describe. Since I didn't like this solution I started looking around to see if there's anything more elegant and bumped into your post. So.. Can you share the solution, Or am I going to need to continue looking around?? :) thanks
The solution goes something like this: Change the accept and visit methods to return a value (accept just passes through the visit method's results). This is very simple in a dynamically typed language. In ruby, even the above accept code will do (a method's last expression's value is returned). In a language like Java (with static typing and a type system with generics) this may look like this: [sourcecode language='java'] public T accept(Visitor visitor) { return visitor.visit(this); } [/sourcecode] A typical expression visitor might specialize T as a number type. This way, the evaluation method could for example be implemented like this: [sourcecode language='java'] public Integer visit(AddExpression expr) { return expr.leftSubExpression().accept(this) + expr.rightSubExpression.accept(this); } [/sourcecode] (This code is untested.) To be honest, it's a bit sad that Java only allows to specialize a generic type using class types, not atomic types like int. I hope that helped. :) Best regards, Günther

New comment