Monday, March 07, 2011

Haskell Parsec

I am going to illustrate the usage of Parsec to parse an expression into an AST. Something that took me quite a while to come up with (with help from the cafe) - Hoping, someone will find this useful

http://legacy.cs.uu.nl/daan/download/parsec/parsec.html has a sample for expression parsing - but that evaluates the expression.

And if you have not looked at http://www.cse.chalmers.se/edu/year/2010/course/TDA341/Papers/parser-hutton.ps - please do so, and fall in love with Haskell all over again :)

Say you have created an AST as follows -


data Tree a = Nil | Node a (Tree a ) (Tree a) deriving (Show)
data Element = Number Float | Plus | Minus | Multiply | Divide deriving (Show)
type AST = Tree Element


And given an expression 1+2, you need to parse it into the above mentioned AST -

Right (Node Plus (Node (Number 1.0) Nil Nil) (Node Multiply (Node (Number 2.0) Nil Nil) (Node (Number 3.0) Nil Nil)))


Full code for it is here - https://github.com/ckkashyap/LearningPrograms/blob/master/Haskell/parsec/FormParse.hs

Beautiful, is it not!

Followers