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