Search code examples
haskellcompiler-constructionalex

Haskell data type pattern matching in Alex


Suppose I have a data type in Haskell like this:

data Token = THEN AlexPosn
            | ELSE AlexPosn

from Alex, I get that:

data AlexPosn = AlexPn !Int !Int !Int
    deriving (Eq,Show)

I am able to do pattern matching like this:

eat_token :: Token -> [Token] -> [Token]
eat_token  (THEN p1)((THEN p2):rest) = rest
eat_token  (ELSE p1)((ELSE p2):rest) = rest

But what I really want to accomplish here is this:

eat_token  (_ p) tk2 = error "Syntax Error at:"++(show p)

However, I get:

Parse error in pattern.

Any suggestions?


Solution

  • Whenever you find yourself wanting to do pattern matching that ignores the constructor like that, it's usually a sign that you want to refactor your type to have a new enumeration field instead of the old data constructor labels:

    data Token = Token TokenType AlexPosn
    data TokenType = THEN | ELSE
    

    Then, you can easily do the pattern match you wanted:

    eat_token (Token _ p) tk2 = error $ "Syntax Error at: " ++ show p