Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; https://stackoverflow.com/questions/60237494/cascading-parsers-in-haskell/60239524#60239524
- ;; by https://stackoverflow.com/users/2383766/z-y-l
- ;; a re-write with MonadComprehensions
- ;; by https://stackoverflow.com/users/849891/will-ness
- newtype Parser a = Parser { parse :: String -> Maybe (a, String) }
- satisfy :: (Char -> Bool) -> Parser Char
- satisfy cond = Parser $ \s -> [(c, cs) | (c:cs) <- pure s, cond c]
- many :: Parser a -> Parser [a]
- many p = Parser $ \s -> [ (c:cs) | (c, s1) <- parse p s
- , (cs, s2) <- parse (many p) s1]
- <|> pure []
- string :: String -> Parser String
- string str = Parser $ \s -> [(str, drop (length str) s) | isPrefixOf str s]
- instance Functor Parser where
- fmap f (Parser p) = Parser $ \s -> [(f x, s1) | (x,s1) <- p s]
- instance Applicative Parser where
- pure a = Parser $ \s -> pure (a, s)
- -- (<*>) :: f (a -> b) -> f a -> f b
- (Parser p) <*> (Parser q) = Parser $ \s -> [(f x, s2) | (f, s1) <- p s
- , (x, s2) <- q s1]
- instance Semigroup a => Semigroup (Parser a) where
- (Parser p) <> (Parser q) = Parser $ \s -> [(r1 <> r2, s2) | (r1, s1) <- p s
- , (r2, s2) <- q s1]
- --- instance (Monoid a, Semigroup (Parser a)) => Monoid (Parser a) where
- instance (Monoid a) => Monoid (Parser a) where
- mempty = pure mempty
- mappend = (<>)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement