This is a library of parser combinators, originally written by Koen Claessen.
It parses all alternatives in parallel, so it never keeps hold of
the beginning of the input string, a common source of space leaks with
other parsers. The (+++) choice combinator is genuinely commutative;
it makes no difference which branch is "shorter".
Transforms a parser into one that does the same, but
in addition returns the exact characters read.
IMPORTANT NOTE: gather gives a runtime error if its first argument
is built using any occurrences of readS_to_P.
Parses the first zero or more characters satisfying the predicate.
Always succeeds, exactly once having consumed all the characters
Hence NOT the same as (many (satisfy p))
Parses the first one or more characters satisfying the predicate.
Fails if none, else succeeds exactly once having consumed all the characters
Hence NOT the same as (many1 (satisfy p))
chainr p op x parses zero or more occurrences of p, separated by op.
Returns a value produced by a right associative application of all
functions returned by op. If there are no occurrences of p, x is
returned.
chainl p op x parses zero or more occurrences of p, separated by op.
Returns a value produced by a left associative application of all
functions returned by op. If there are no occurrences of p, x is
returned.
Converts a parser into a Haskell ReadS-style function.
This is the main way in which you can "run" a ReadP parser:
the expanded type is
readP_to_S :: ReadP a -> String -> [(a,String)]
Converts a Haskell ReadS-style function into a parser.
Warning: This introduces local backtracking in the resulting
parser, and therefore a possible inefficiency.
Properties
0 declarations
The following are QuickCheck specifications of what the combinators do.
These can be seen as formal specifications of the behavior of the
combinators.
For some values, we only care about the lists contents, not their order,
(=~) :: Ord a => [a] -> [a] -> Bool
xs =~ ys = sort xs == sort ys
Here follow the properties:
Example1 expression
>>> readP_to_S get [][]
Property
prop> \c str -> readP_to_S get (c:str) == [(c, str)]
Property
prop> \str -> readP_to_S look str == [(str, str)]
Property
prop> \str -> readP_to_S pfail str == []
Property
prop> \x str -> readP_to_S (return x) s == [(x,s)]
prop_Bind p k s =
readP_to_S (p >>= k) s =~
[ ys''
| (x,s') <- readP_to_S p s
, ys'' <- readP_to_S (k (x::Int)) s'
]
prop_Plus p q s =
readP_to_S (p +++ q) s =~
(readP_to_S p s ++ readP_to_S q s)
prop_LeftPlus p q s =
readP_to_S (p <++ q) s =~
(readP_to_S p s +<+ readP_to_S q s)
where
[] +<+ ys = ys
xs +<+ _ = xs
prop_Gather s =
forAll readPWithoutReadS $ \p ->
readP_to_S (gather p) s =~
[ ((pre,x::Int),s')
| (x,s') <- readP_to_S p s
, let pre = take (length s - length s') s
]