[Haskell-beginners] expression parser
Daniel Fischer
daniel.is.fischer at web.de
Tue Dec 22 16:10:22 EST 2009
Am Dienstag 22 Dezember 2009 21:48:11 schrieb John Moore:
> Hi,
> Could some one point out what I'm doing wrong below. This is a parser
> which takes an arithmetic expression built up from single digits. Turns
> 3*4+2 into (3*4)+2 etc.It giving me the last expression in a do statement
> or parse error on ->
>
> (+++) :: Parser a -> Parser a -> Parser a
> expr :: term( '+' expr |"")
> term -> factor('*' term |"")
What's happened here?
A part of your grammar seems to have slipped into the code.
>
> expr :: Parser Int
> expr = do t <- term
> do char '+'
> e <- expr
> return (t + e)
> +++ return t
>
> term :: Parser Int
> term = do f <- factor
> do char '*'
> t <- term
> return (f * t)
> +++ return f
>
> factor :: Parser Int
> factor = do d <- digit
> return (digitToInt d)
> +++ do char '('
> e <- expr
> char ')'
> return e
>
> eval :: String -> Int
> eval xs = fst(head(parse expr xs))
Maybe it's just the mail programme, but what arrived here had wrong indentation.
In expr, the inner do-block isn't aligned with "t <- term".
In term, the "return (f * t)" isn't aligned with "char '*'" and "t <- term" and the whole
inner dop-block isn't aligned with "f <- factor".
In factor, "return (digitToInt d)" isn't aligned with "d <- digit" and in the second
block, "char ')'" and "return e" aren't aligned with "char'('" and "e <- expr".
Properly aligned and with an implementation of (+++) instead of grammar productions, it
should work.
>
>
> John
More information about the Beginners
mailing list