import Data.Char
import Text.Read
-import Text.ParserCombinators.ReadP hiding ((+++), choice)
+import Text.ParserCombinators.ReadP hiding ((+++), (<++), choice)
data Expr = Num Double
| Var String
| BinOp BinOp Expr Expr
| Call String [Expr]
| If Expr Expr Expr
+ | For String Expr Expr (Maybe Expr) Expr
deriving Show
data BinOp = Add | Sub | Mul | Cmp Ordering
, parseVar
, parseCall
, parseIf
+ , parseFor
, parseBinOp "<" 10 (Cmp LT)
, parseBinOp ">" 10 (Cmp GT)
, parseBinOp "==" 10 (Cmp EQ)
parseVar = Var <$> lift (munch1 isAlpha)
parseBinOp s prc op = prec prc $ do
a <- step readPrec
- lift $ do
- skipSpaces
- string s
- skipSpaces
+ spaced $ string s
b <- readPrec
return (BinOp op a b)
parseCall = do
(skipSpaces >> char ',' >> skipSpaces)
return (Call func params)
parseIf = do
- lift $ skipSpaces >> string "if" >> skipSpaces
+ spaced $ string "if"
cond <- readPrec
- lift $ skipSpaces >> string "then" >> skipSpaces
+ spaced $ string "then"
thenE <- readPrec
- lift $ skipSpaces >> string "else" >> skipSpaces
+ spaced $ string "else"
elseE <- readPrec
return (If cond thenE elseE)
+ parseFor = do
+ spaced $ string "for"
+ identifier <- lift (munch1 isAlpha)
+ spaced $ char '='
+ start <- readPrec
+ spaced $ char ','
+ cond <- readPrec
+ stp <- (spaced (char ',') >> Just <$> step readPrec)
+ <++ pure Nothing
+ spaced $ string "in"
+ body <- readPrec
+ return (For identifier start cond stp body)
+ spaced f = lift $ skipSpaces >> f >> skipSpaces
data Prototype = Prototype String [String]
deriving Show