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 has a sample for expression parsing - but that evaluates the expression.

And if you have not looked at - 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 -

Beautiful, is it not!