I\'ve been playing with Haskell for about a month. For my first \"real\" Haskell project I\'m writing a parts-of-speech tagger. As part of this project I have a type called
Don't use the Haskell lexer then. The read
functions use ParSec, which you can find an excellent introduction to in the Real World Haskell book.
Here's some code that seems to work,
import Text.Read
import Text.ParserCombinators.ReadP hiding (choice)
import Text.ParserCombinators.ReadPrec hiding (choice)
data Tag = CC | CD | DT | EX | FW | IN | JJ | JJR | JJS deriving (Show)
strValMap = map (\(x, y) -> lift $ string x >> return y)
instance Read Tag where
readPrec = choice $ strValMap [
("CC", CC),
("CD", CD),
("JJ$", JJS)
]
just run it with
(read "JJ$") :: Tag
The code is pretty self explanatory. The string x
parser monad matches x
, and if it succeeds (doesn't throw an exception), then y
is returned. We use choice
to select among all of these. It will backtrack appropriately, so if you add a CCC
constructor, then CC
partially matching "CCC" will fail later, and it will backtrack to CCC
. Of course, if you don't need this, then use the <|>
combinator.