[Haskell-cafe] question on traversing syntax tree
xiongyf04 at sei.pku.edu.cn
Thu Aug 24 05:53:24 EDT 2006
I am writing a compiler using Haskell. After the compiler parses program, the program is stored into an syntax tree stucture defined blew:
= Plus Exp Term
| Minus Exp Term
| Term Term
= Times Term Factor
| Div Term Factor
| Factor Factor
This is just part of the definition. The full tree contains much more definition than this. Now I want to adjust the syntax-tree. However, I don't need to adjust all the data types, but a small subset of the syntax tree. e.g. I might adjust the "Times" data like the following, but not modify the rest of the syntax tree:
transformTerm (Times t f) = Times t (FactorInt 100)
However, in order to apply the modification like this, I have to write a series of function to traverse the tree until I get to the Term data type. e.g. I have to define:
transformExp (Plus e t) = Plus (transformExp e) (transformTerm t)
transformExp (Minus e t) = Minus (transformExp e)(transformTerm t)
transformTerm (Term t) = ...
This is tedious and error-prone. I want to know if there some means in Haskell to write a single "generic" function to traverse the syntax tree and only stop on the "Term" data type. Can anyone tell me something about it? Thanks a lot.
Xiong, Yingfei (熊英飞)
Institute of Software
School of Electronics Engineering and Computer Science
Beijing, 100871, PRC.
More information about the Haskell-Cafe