Zemyla

ReadP as a list

Jul 12th, 2026
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. -- Okay, ReadP should be a MonadFix. It can, if you have the internal representation, be converted to `ReadNT []`, where:
  2. newtype ReadNT m a = ReadNT { runReadNT :: String -> m (a, Either Int String) }
  3.  
  4. deriving instance Functor m => Functor (ReadNT m)
  5.  
  6. instance Monad m => Applicative (ReadNT m) where { pure a = ReadNT $ const $ pure (a, Left 0); (<*>) = ap }
  7.  
  8. instance Monad m => Monad (ReadNT m) where
  9. ReadNT m >>= f = ReadNT $ \s -> do
  10. (a, r) <- m s
  11. case r of
  12. Left i -> do
  13. (b, t) -> runReadNT (f a) $ drop i s
  14. case t of
  15. Left j -> (b, Left (i + j))
  16. Right sn -> (b, Right sn)
  17. Right sr -> do
  18. (b, t) -> runReadNT (f a) sr
  19. case t of
  20. Left j -> (b, Right (drop j sr))
  21. Right sn -> (b, Right sn)
  22.  
  23. -- It has the obvious MonadFix instance.
  24. instance MonadFix m => MonadFix (ReadNT m) where
  25. mfix f = ReadNT $ \s -> mfix $ \ ~(a, _) -> runReadNT (f a) s
Advertisement
Add Comment
Please, Sign In to add comment