[Haskell-cafe] question on traversing syntax tree
Xiong Yingfei
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:
......
data Exp
= Plus Exp Term
| Minus Exp Term
| Term Term
deriving Show
data Term
= Times Term Factor
| Div Term Factor
| Factor Factor
deriving Show
......
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 (熊英飞)
Ph.D. Student
Institute of Software
School of Electronics Engineering and Computer Science
Peking University
Beijing, 100871, PRC.
Web: http://xiong.yingfei.googlepages.com
More information about the Haskell-Cafe
mailing list