Wednesday, 3 December 2008

F# Monadic Parser - Calculator Example.

//F# Monadic Parser - Calculator Example :))) 

// Grammar
//expr ::= expr addop term j term
//term ::= term mulop factor j factor
//factor ::= digit j ( expr )
//digit ::= 0 j 1 j : : : j 9
//addop ::= + j -
//mulop ::= * j /

let addOp = parser { let! _ = symb "+"
return (+) } +++ parser { let! _ = symb "-"
return (-) }
let mulOp = parser { let! _ = symb "*"
return (*) } +++ parser { let! _ = symb "/"
return (/) }
let digit = parser { let! x = token (sat (fun ch -> Char.IsDigit(ch)))
return Char.GetNumericValue(x) - Char.GetNumericValue('0') }

let rec expr = chainl1 term addOp
and term = chainl1 factor mulOp
and factor = digit +++ parser { let! _ = symb "("
let! n = expr
let! _ = symb ")"
return n }

let parse s = match apply expr s with
| [] -> failwith "failed to parse"
| (ret, _)::xs -> ret

parse "5 * (3 + 4)"
|> printf "%A"




No comments: