7 import Control.Applicative
11 -- A parser for a value of type a is a function which takes a String
12 -- represnting the input to be parsed, and succeeds or fails; if it
13 -- succeeds, it returns the parsed value along with the remainder of
15 newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
17 -- For example, 'satisfy' takes a predicate on Char, and constructs a
18 -- parser which succeeds only if it sees a Char that satisfies the
19 -- predicate (which it then returns). If it encounters a Char that
20 -- does not satisfy the predicate (or an empty input), it fails.
21 satisfy :: (Char -> Bool) -> Parser Char
24 f [] = Nothing -- fail on the empty input
25 f (x:xs) -- check if x satisfies the predicate
26 -- if so, return x along with the remainder
27 -- of the input (that is, xs)
29 | otherwise = Nothing -- otherwise, fail
31 -- Using satisfy, we can define the parser 'char c' which expects to
32 -- see exactly the character c, and fails otherwise.
33 char :: Char -> Parser Char
34 char c = satisfy (== c)
38 *Parser> runParser (satisfy isUpper) "ABC"
40 *Parser> runParser (satisfy isUpper) "abc"
42 *Parser> runParser (char 'x') "xyz"
47 -- For convenience, we've also provided a parser for positive
49 posInt :: Parser Integer
54 | otherwise = Just (read ns, rest)
55 where (ns, rest) = span isDigit xs
57 ------------------------------------------------------------
58 -- Your code goes below here
59 ------------------------------------------------------------