Advertisement
Guest User

MonadComprehensions is shorter than Do is shorter than

a guest
Feb 18th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ;; https://stackoverflow.com/questions/60237494/cascading-parsers-in-haskell/60239524#60239524
  2. ;; by https://stackoverflow.com/users/2383766/z-y-l
  3.  
  4. ;; a re-write with MonadComprehensions
  5. ;; by https://stackoverflow.com/users/849891/will-ness
  6.  
  7. newtype Parser a = Parser { parse :: String -> Maybe (a, String) }
  8.  
  9. satisfy :: (Char -> Bool) -> Parser Char
  10. satisfy cond = Parser $ \s -> [(c, cs) | (c:cs) <- pure s, cond c]
  11.  
  12. many :: Parser a -> Parser [a]
  13. many p = Parser $ \s -> [ (c:cs) | (c, s1) <- parse p s
  14.                                  , (cs, s2) <- parse (many p) s1]
  15.                         <|> pure []
  16.  
  17. string :: String -> Parser String
  18. string str = Parser $ \s -> [(str, drop (length str) s) | isPrefixOf str s]
  19.  
  20. instance Functor Parser where
  21.   fmap f (Parser p) = Parser $ \s -> [(f x, s1) | (x,s1) <- p s]
  22.  
  23. instance Applicative Parser where
  24.   pure a = Parser $ \s -> pure (a, s)
  25.   -- (<*>) :: f (a -> b) -> f a -> f b
  26.   (Parser p) <*> (Parser q) = Parser $ \s -> [(f x, s2) | (f, s1) <- p s
  27.                                                         , (x, s2) <- q s1]
  28.  
  29. instance Semigroup a => Semigroup (Parser a) where
  30.   (Parser p) <> (Parser q) = Parser $ \s -> [(r1 <> r2, s2) | (r1, s1) <- p s
  31.                                                             , (r2, s2) <- q s1]
  32.                          
  33. --- instance (Monoid a, Semigroup (Parser a)) => Monoid (Parser a) where
  34. instance (Monoid a) => Monoid (Parser a) where
  35.   mempty = pure mempty
  36.   mappend = (<>)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement