sdiehl / write-you-a-haskell

Building a modern functional compiler from first principles. (http://dev.stephendiehl.com/fun/)
MIT License
3.34k stars 256 forks source link

Parser/Type error for + and - #98

Open jonmountjoy opened 7 years ago

jonmountjoy commented 7 years ago

I think https://github.com/sdiehl/write-you-a-haskell/pull/90 from @jeffreyrosenbluth introduced a bug. At least, I think it was that commit.

Prior to this commit (ie. using #1e609fb), you can do something like the following:

Poly> 2 + 3
5 : Int

Now, I get the following:

Poly> 2 + 3
Cannot unify types:
    Int
with
    Int -> a

Weirdly, it works for the * operator, but fails only for + and -:

I suspect there's something weird going on in the parser because:

Poly> 2 + x
"<stdin>" (line 1, column 5):
unexpected "x"
expecting digit
Poly> 2 * x
4 : Int
jonmountjoy commented 7 years ago

In fact, the error is on this line. If you revert the way terms are parsed, all will be good. ie. Ex.buildExpressionParser table aexp. I don't quite understand the new code, and why it sort of works for some operators...

tly000 commented 7 years ago

I think i found the problem: The "+" character is parsed as a positive sign inside Tok.integer lexer. I fixed the problem this way:

Parser.hs, line 20

integer :: Parser Integer
integer = Tok.natural lexer

Parser.hs line, 82

aexp :: Parser Expr
aexp = do
  r <- many1 $ choice [parens expr,bool,number,ifthen,fix,try letrecin, letin, lambda, variable]
  return $ foldr1 App r

expr :: Parser Expr
expr = Ex.buildExpressionParser table aexp