Permalink
Browse files

Arithmetic expression parser

  • Loading branch information...
1 parent 7c13a31 commit 5dca9ebecfa798aa700eef5dbd6e93bb1d0ae5b5 @tianyicui committed Nov 29, 2010
Showing with 33 additions and 0 deletions.
  1. +33 −0 ch08/ExpParser.hs
View
@@ -0,0 +1,33 @@
+module ExpParser where
+
+import Parser
+
+expr, term, factor :: Parser Int
+
+expr =
+ do t <- term
+ do symbol "+"
+ e <- expr
+ return (t + e)
+ +++ return t
+
+term =
+ do f <- factor
+ do symbol "*"
+ t <- term
+ return (f * t)
+ +++ return f
+
+factor =
+ do symbol "("
+ e <- expr
+ symbol ")"
+ return e
+ +++ natural
+
+eval :: String -> Int
+eval xs =
+ case parse expr xs of
+ [(n,[])] -> n
+ [(_,out)] -> error ("unused input " ++ out)
+ [] -> error "invalid input"

0 comments on commit 5dca9eb

Please sign in to comment.