implementation module yard import StdTuple import StdClass import Data.Functor import Data.Either import Control.Monad import Control.Applicative from Data.Func import $ runParser :: (Parser a b) [a] -> (Either Error b, [a]) runParser (Parser f) i = f i instance Functor (Parser a) where //fmap f m = liftM f m fmap g p = Parser \i -> case runParser p i of (Right r, rest) = (Right $ g r, rest) (Left e, rest) = (Left e, rest) instance Applicative (Parser a) where pure a = Parser \i -> (Right a, i) //(<*>) sf p = ap sf p (<*>) pf p = Parser \i -> case runParser pf i of (Right f, rest) = runParser (fmap f p) rest (Left e, rest) = (Left e, rest) instance Monad (Parser a) where bind p f = Parser \i -> case runParser p i of (Right r, rest) = runParser (f r) rest (Left e, rest) = (Left e, rest) //some, many, optional and l instance Alternative (Parser a) where empty = Parser \i -> (Left ParseException, i) (<|>) p1 p2 = Parser \i -> case runParser p1 i of (Right r, rest) = (Right r, rest) (Left _, rest) = runParser p2 i fail :: Parser a b fail = empty top :: Parser a a top = Parser \i -> case i of [] = (Left ParseException, []) [x:xs] = (Right x, xs) satisfy :: (a -> Bool) -> Parser a a satisfy f = top >>= \r -> if (f r) (return r) fail item :: a -> Parser a a | Eq a item a = satisfy ((==)a) list :: [a] -> Parser a [a] | Eq a list as = mapM item as