当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - How to convert an expression in Haskell to a Tree structure to get information in the expression?

问题描述:

is there a way to convert an expression in Haskell language to a Tree like format and extract information from each node. Or Generate all possible trees for a given expression ?

Ex: add 5 3

This is tree where, 3 and 5 are leaf nodes and "add" as the root. So what I need is to get decompose the above expression so that I can do further analysis on the expression.

eg: * to know what are the values that I'm going to "add".

* to know what is the operation that I'm performing over the given numbers (here "add", also it could be "subtraction", "multiplication" etc.)

Really appreciate your help :)

网友答案:

You could use Template Haskell:

Language.Haskell.TH> runQ [e|3 + 5|]
InfixE (Just (LitE (IntegerL 3))) (VarE GHC.Num.+) (Just (LitE (IntegerL 5)))

Or haskell-src-exts:

Language.Haskell.Exts> parse "3 + 5" :: ParseResult Exp
ParseOk (InfixApp (Lit (Int 3)) (QVarOp (UnQual (Symbol "+"))) (Lit (Int 5)))
分享给朋友:
您可能感兴趣的文章:
随机阅读: