sergeyz
sergeyz

Reputation: 1328

Add additional info to haskell type

I have Token data type in my program. It looks something like that:

data Token
    = StringToken Strin
    | NumberToken Integer
    | IfToken
    | ElseToken
    ... -- lots of tokens here

I use this data type in my parser ant it works fine. But now I want to append some additional info to tokens (source location information). So I can change my data type declaration and use records:

data Token
    = StringToken {value :: String, srcLoc :: SourceLocation}
    | NumberToken {value :: String, srcLoc :: SourceLocation}
    | IfToken {srcLoc :: SourceLocation}
    | ElseToken {srcLoc :: SourceLocation}
    ... -- lots of tokens here

But this solution doesn't seem very practical and beautiful to me. So is there better solution for this problem? Thanks.

Upvotes: 3

Views: 174

Answers (1)

AndrewC
AndrewC

Reputation: 32455

Yes:

data TokenLoc = TokenLoc {tok::Token , srcLoc::SourceLocation}

This stores the token and the location together, but cleanly keeps them separate, avoiding the repetition.

Upvotes: 9

Related Questions