[Haskell-beginners] Simple lookahead with Parsec

Derek Thurn derek at thurn.ca
Fri Mar 19 11:14:00 EDT 2010


Hello. I'm just starting out with Parsec and Haskell, and I want to
parse a very simple grammar with it. I think I may not understand how
to use try correctly.

Here's a simplified version of my grammar:

myType = try (primitiveType) <|> arrayType
primitiveType = do {reserved "int"; return "primitive"}
arrayType = do { primitiveType; symbol "["; symbol "]"; return "array"}

Basically, I want to use lookahead to produce the result "array" on
inputs like "int[]" and the result "primitive" on inputs like "int".
However, no matter what I do with the try function, I am not able to
get what I expect. When I run this code using the runLex function
described in the Parsec documentation, it chokes on "int[]", saying
that the '[' character was unexpected.

I've discovered that switching the order of primitiveType and
arrayType solves this, which makes sense, but I still expected it to
be possible to use try() in this manner to resolve the error with
lookahead. Am I doing something wrong?

(I've got some boilerplate code form the Parsec documentation defined
as well, but I didn't include it for brevity's sake. Reserved and
symbol are defined how you'd expect.)


More information about the Beginners mailing list