[Haskell-beginners] variable parser
John Moore
john.moore54 at gmail.com
Sat Jan 9 12:45:23 EST 2010
Hi,
I just want to add a new parser for variables but this doesn't seem to
work can anybody tell me what I'm doing wrong?
module ExprSyn where
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
runExpr :: String -> IO ()
runExpr str = case runParser expr () " " str of
Left err -> putStrLn "Error:" >> print err
Right val -> print val
demo1 = runExpr "2+5"
data Expr = Mul Expr Expr
| Div Expr Expr
| Add Expr Expr
| Sub Expr Expr
| Val Float
|Let String Expr Expr
| Var String
deriving (Eq,Show)
expr :: Parser Expr
expr = variable <|> buildExpressionParser table factor
<?> "expression"
table :: [[Operator Char st Expr]]
table = [[op "*" Mul AssocLeft, op "/" Div AssocLeft]
,[op "+" Add AssocLeft, op "-" Sub AssocLeft]
]
where
op s f assoc
= Infix (do{ string s; return f}) assoc
factor :: Parser Expr
factor = do{ char '('
; x <- expr
; char ')'
; return x
}
<|> number
<|> variable
<?> "simple expression"
variable :: Parser Expr
variable = do { b <- letter
; do { cs <- word
;return (c:cs)
<|> return [c]
<|> number
}
number :: Parser Expr
number = do{ ds <- many1 digit
; return (Val $ read ds)
}
John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100109/ad3167d4/attachment.html
More information about the Beginners
mailing list