module AST where
import Text.Read
-import Text.ParserCombinators.ReadP hiding ((+++))
+import Text.ParserCombinators.ReadP hiding ((+++), choice)
+data BinOpType = Add | Sub | Mul
+ deriving Show
data Expr = Num Float
- | Add Expr Expr
+ | BinOp BinOpType Expr Expr
deriving Show
instance Read Expr where
- readPrec = parseNum +++ parseAdd
+ readPrec = choice [ parseNum
+ , parseBinOp '+' Add
+ , parseBinOp '-' Sub
+ , parseBinOp '*' Mul
+ ]
where parseNum = Num <$> readPrec
- parseAdd = step $ do
+ parseBinOp c typ = step $ do
a <- prec 11 readPrec
lift $ do
skipSpaces
- char '+'
+ char c
skipSpaces
b <- readPrec
- return (Add a b)
+ return (BinOp typ a b)