6
\$\begingroup\$

I'm creating list of Tokens from input [Char] stream using Parsec v3. The definition of Token looks like this:

data Token = CharKeyword | OpeningBracket | Identifier String | Natural Int

As result of calling parse lexComb "" inputStream i have [Token]. Everything OK so far.

Now i want to parse this list of tokens using another parse invocation, but i've found myself writing such boilerplate code for every Token constructor:

psOpBracket = tokenPrim s np p
 where
 s _ = "'{'"
 p (OpeningBracket) = Just Nothing
 p _ = Nothing
 np pos _ _ = pos

another example:

psPacketName = tokenPrim s np p
 where
 s x = x
 p (Identifier x) = Just x
 p _ = Nothing
 np pos _ _ = pos

I wonder if it's right to use tokenPrim at all. And if so, is there any way to automatically generate parsers for every token? Maybe Template Haskell?

asked Dec 11, 2011 at 14:23
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I've solved it by using Text.ParserCombinators.Parsec.GeneralizedToken from MissingH package:

psOpBracket = tokeng (\x -> case x of TokOpBracket -> Just Nothing ; _ -> Nothing)

I had to use tokenPrim for cases when Token constructor takes arguments, though.

answered Dec 16, 2011 at 15:14
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.