From: Bernhard Brodowsky Date: 2010-04-28T03:13:05+09:00 Subject: Re: Visitor pattern Caleb Clausen wrote: > On 4/27/10, Bernhard Brodowsky wrote: >> visitors, like for example a pretty printer or something to compare ASTs >> (useful for unit tests) >> I could just add this functionality to the elements of the AST directly, >> but somehow, I don't like this because I always have to search my ~30 >> classes that represent syntax units and implement one method in each of >> them. Instead, it's much more comfortable to just write one new class. >> >> What do you think about that? Is it really that bad to use the visitor >> pattern in Ruby? And if yes, what is the reason for this? > > Personally, I prefer to write 30 different SyntaxNode#visit methods > (or whatever you call them). But it's really a matter of taste. > > If you create an actual visitor class (or method), I think you'll find > at the core of it a big ugly case statement. I like case statements > more than most people, but when they get bigger than a page, I get > nervous. Ok, of course, this would be quite terrible, but I think you can do it better. You just implement the accept methods slightly different. The accept method in Plus calls the method visit_plus on the visitor, the accept method in Or calls the method visit_or on the visitor and so one. Like that you can get around case statements, I think. You just have to write many methods in the visitor. But right now I think, I still won't use the visitor pattern since the visitor pattern is good to add new operations, but bad to add new elements. And while I'll only add few operations like pretty printing or something similar, I think I will introduce many new elements. > > (The ideal solution would be to have a set of pattern-matching rules > and actions to be taken when those patterns are found in the tree. The > patterns would be more complicated than simply node classes; they > could depend on properties of the nodes. This starts to look a lot > like haskell or maybe antlr. I've tried hard to get this to work in > ruby, and successfully done the pattern-matching part but getting > actions to work as well turned out to be surprisingly difficult. > AFAIK, no one else has done any better.) Ok, it seems you have a lot of experience with real interpreters. Of course, it would be cool to do something like Haskell, but I think for my purposes, the model with the different node classes is sufficient. It's only my first interpreter for a very small language. But isn't this pretty orthogonal, anyway? I mean, you could just use some additional conditionals in the node classes as well as in the visitor to implement this, or do I misunderstand this? -- Posted via http://www.ruby-forum.com/.