stats_model
stats_model

Reputation: 121

Writing parsers with Text.ParserCombinators

In class, we wrote parsers by defining our own Parser type and this gave us a lot of flexibility. For example, if we wanted to make code and parse out "[at]" as '@', we could write

atParser = Parser $ \s ->
    case s of
        w:x:y:z:zs ->
            | (w:x:y:z:[]) == "[at]" = ['@',zs]
            | otherwise = []
        zs -> []

However, I cannot figure out how to implement this sort of parser using Text.ParserCombinators. Is it possible?

Thanks

Upvotes: 0

Views: 39

Answers (1)

hao
hao

Reputation: 10238

I believe you're looking for the string combinator.

λ> :set -package parsec
package flags have changed, resetting and loading new packages...

λ> import Text.Parsec

λ> :t string
string :: Stream s m Char => String -> ParsecT s u m String

λ> parse (string "[at]") "" "[at]"
Right "[at]"

λ> parse (string "[at]") "" "[at"
Left (line 1, column 1):
unexpected end of input
expecting "[at]"

λ> parse ('@' <$ string "[at]") "" "[at]"
Right '@'

Upvotes: 1

Related Questions