4 Parser is a function from a string and a position in the
\r
5 string to a possible semantics of a substring and the
\r
6 end of the substring.
\r
8 data Parser a = Parser (String -> Integer -> Maybe (a, Integer))
\r
10 runParser :: Parser a -> String -> Integer -> Maybe (a, Integer)
\r
11 runParser (Parser f) = f
\r
13 instance Functor Parser where
\r
14 fmap f (Parser p) = Parser (\input pos -> match p input pos with
\r
16 Just (a, newPos) -> Just (f a, newPos)
\r
19 instance Monad Parser where
\r
20 return x = Parser (\_ pos -> Just (x, pos))
\r
21 (pa >>= f) = Parser (\input pos -> match runParser pa input pos with
\r
23 Just (a, newPos) -> runParser (f a) input newPos
\r
26 (|||) :: Parser a -> Parser a -> Parser a
\r
27 Parser a ||| Parser b = Parser (\input pos -> match a input pos with
\r
28 Nothing -> b input pos
\r
32 keyword :: String -> Parser ()
\r
33 keyword word = Parser (\input pos ->
\r
34 if regionMatches word 0 input pos (length word)
\r
35 then Just ((), pos + (length word))
\r
39 data List a = Nil | Cons a (List a)
\r
41 listSepL :: Parser () -> Parser a -> Parser (List a)
\r
42 listSepL sep el = mdo
\r
44 tail <- (sep >> listSepL sep el) ||| return Nil
\r
45 return (Cons head tail)
\r
47 fromList :: List a -> [a]
\r
48 fromList = unfoldr gen
\r
51 gen (Cons h t) = Just (h, t)
\r
53 listSep :: Parser () -> Parser a -> Parser [a]
\r
54 listSep sep el = fmap fromList (listSepL sep el)
\r
56 aOrB = (keyword "a" >> return "a") ||| (keyword "b" >> return "b")
\r
58 myParser = listSep (keyword ",") aOrB
\r
60 main = show (runParser myParser "a,b,b,a" 0)
\r
62 Just (["a", "b", "b", "a"], 7)