Guest User

Untitled

a guest
Aug 16th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import Control.Monad
  2. import Control.Monad.Trans.Class
  3. import Control.Monad.Trans.State
  4. import Control.Monad.Trans.Maybe
  5. import Control.Monad.IO.Class
  6.  
  7. type Stack = [String]
  8.  
  9. pop :: Stack -> (Maybe String, Stack)
  10. pop (x:xs) = (Just x, xs)
  11. pop [] = (Nothing, [])
  12.  
  13. push :: String -> Stack -> ((), Stack)
  14. push s xs = ((), s:xs)
  15.  
  16. mainLoop :: StateT Stack (MaybeT IO) ()
  17. mainLoop = do
  18. input <- liftIO getLine
  19. if null input
  20. then do
  21. Just x <- state pop
  22. liftIO . putStrLn $ x
  23. else state $ push input
  24. mainLoop
  25.  
  26. main = runMaybeT (runStateT mainLoop [])
  27.  
  28. pop :: Monad m
  29. => StateT [a] m (Maybe a)
  30. pop = do
  31. s <- get
  32. case s of
  33. x : s' -> Just x <$ put s'
  34. [] -> pure Nothing
  35.  
  36. push :: Monad m
  37. => a -> StateT [a] ()
  38. push a = modify (a :)
  39.  
  40. pop :: MonadState [a] m
  41. => m (Maybe a)
  42. push :: MonadState [a] m
  43. => a -> m a
  44.  
  45. s -> MaybeT m (a, s)
  46.  
  47. s -> m (Maybe (a, s))
  48.  
  49. StateT s m (Maybe a)
  50.  
  51. s -> m (Maybe a, s)
  52.  
  53. mainLoop :: MaybeT (StateT Stack IO) x
  54. mainLoop = do
  55. input <- liftIO getLine
  56. if null input
  57. then do
  58. -- No pattern match!
  59. x <- MaybeT pop
  60. liftIO . putStrLn $ x
  61. else push input
  62. mainLoop
  63.  
  64. pop :: (MonadState [a] m, MonadFail m)
  65. => m a
  66. pop = do
  67. s <- get
  68. case s of
  69. x : s' -> x <$ put s'
  70. [] -> fail "Empty stack"
  71.  
  72. mainLoop :: ( MonadState Stack m
  73. , MonadIO m
  74. , MonadFail m )
  75. => m x
  76. mainLoop = do
  77. input <- liftIO getLine
  78. if null input
  79. then do
  80. x <- pop
  81. liftIO . putStrLn $ x
  82. else push input
  83. mainLoop
Add Comment
Please, Sign In to add comment