Ad
Parsing
Algorithms
Logic
Strings
Monads
Data Structures
Functional Programming
Code
Diff
  • {-# LANGUAGE DeriveFunctor, TupleSections, LambdaCase #-}
    module MonadicParsing where
    
    import Control.Applicative
    import Control.Monad
    
    newtype Parser a = Parser { runParser :: String -> [(a, String)] }
        deriving Functor
    
    instance Applicative Parser where
        pure a = Parser $ pure . (a,)
        (<*>) = ap
    
    instance Monad Parser where
        return = pure
        Parser p >>= f = Parser $ \s -> concatMap (uncurry (runParser.f)) $ p s
    
    instance Alternative Parser where
        empty = Parser $ pure []
        Parser p <|> Parser q = Parser $ liftA2 (++) p q
    
    
    pred1 :: (Char -> Bool) -> Parser Char
    pred1 p = Parser $ \case c:cs | p c -> [(c, cs)]; _ -> []
    
    char :: Char -> Parser Char
    char = pred1 . (==)
    
    str :: String -> Parser String
    str = mapM char
    
    • {-# LANGUAGE DeriveFunctor, TupleSections #-}
    • {-# LANGUAGE DeriveFunctor, TupleSections, LambdaCase #-}
    • module MonadicParsing where
    • import Control.Applicative
    • import Control.Monad
    • newtype Parser a = Parser { runParser :: String -> [(a, String)] }
    • deriving Functor
    • instance Applicative Parser where
    • pure a = Parser $ pure . (a,)
    • (<*>) = ap
    • instance Monad Parser where
    • return a = Parser $ return . (a,)
    • return = pure
    • Parser p >>= f = Parser $ \s -> concatMap (uncurry (runParser.f)) $ p s
    • instance Alternative Parser where
    • empty = Parser $ pure []
    • Parser p <|> Parser q = Parser $ liftA2 (++) p q
    • pred1 :: (Char -> Bool) -> Parser Char
    • pred1 p = Parser $ \case c:cs | p c -> [(c, cs)]; _ -> []
    • char :: Char -> Parser Char
    • char = pred1 . (==)
    • str :: String -> Parser String
    • str = mapM char