1 module AParser (Parser, runParser, satisfy, char, posInt) where
3 import Control.Applicative
6 newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
8 satisfy :: (Char -> Bool) -> Parser Char
16 char :: Char -> Parser Char
17 char c = satisfy (== c)
19 posInt :: Parser Integer
24 | otherwise = Just (read ns, rest)
25 where (ns, rest) = span isDigit xs
27 inParser f = Parser . f . runParser
29 first :: (a -> b) -> (a,c) -> (b,c)
30 first f (x,y) = (f x, y)
32 instance Functor Parser where
33 fmap = inParser . fmap . fmap . first
35 instance Applicative Parser where
36 pure a = Parser (\s -> Just (a, s))
37 (Parser fp) <*> xp = Parser $ \s ->
40 Just (f,s') -> runParser (f <$> xp) s'
42 instance Alternative Parser where
43 empty = Parser (const Nothing)
44 Parser p1 <|> Parser p2 = Parser $ liftA2 (<|>) p1 p2