Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. {-# LANGUAGE MultiParamTypeClasses #-}
  2.  
  3.  
  4. data State s a = State (s -> (a, s))
  5.  
  6. instance Functor (State s) where
  7. fmap f (State g) = State $ \s -> case g s of
  8. (a, s') -> (f a, s')
  9.  
  10. instance Monad (State s) where
  11. return x = State $ \s -> (x, s)
  12. State func >>= f = State $ \s -> case func s of
  13. (val, s') -> case f val of
  14. State func' -> func' s'
  15.  
  16. instance Applicative (State s) where
  17. pure = return
  18. a <*> b = do
  19. f <- a
  20. x <- b
  21. return (f x)
  22.  
  23.  
  24.  
  25. class MonadState m s where
  26. get :: m s s
  27. put :: s -> m s ()
  28.  
  29.  
  30. instance MonadState State s where
  31. get = State $ \s -> (s, s)
  32. put s = State $ \_ -> (s, ())
  33.  
  34. type StackProgram a = State [Int] a
  35.  
  36. push :: Int -> StackProgram ()
  37. push x = do
  38. stack <- get
  39. put (x:stack)
  40.  
  41. put :: StackProgram Int
  42. put = do
  43. stack <- get
  44. put (tail stack)
  45. return (head stack)
  46.  
  47. example :: StackProgram Int
  48. example = do
  49. push 2
  50. push 3
  51. a <- pop
  52. b <- pop
  53. push (a + b)
  54. pop
  55.  
  56.  
  57. newtype DBOp s a = DBOp (s -> IO (s, a))
  58.  
  59. instance Functor (DBOp s) where
  60. fmap f (DBOp g) = DBOp $ \s -> case g s of
  61. (a, s') -> (f a, s')
  62.  
  63. instance Monad (DBOp s) where
  64. return x = DBOp $ \s -> return (x, s)
  65. DBOp func >>= f = DBOp $ \s -> func s >>= \res -> case res of
  66. (val, s') -> f val >>= \res' -> case res' of
  67. DBOp func' -> func' s
  68.  
  69. instance Applicative (DBOp s) where
  70. pure = return
  71. a <*> b = do
  72. f <- a
  73. x <- b
  74. return (f x)
  75.  
  76. instance MonadState DBOp s where
  77. get = DBOp $ \s -> return (s, s)
  78. put s = DBOp $ \_ -> return (s, ())
  79.  
  80.  
  81. connect :: String -> DBOp Connection ()
  82. connect = undefined
  83.  
  84. update :: String -> String -> DBOp Connection ()
  85. update = undefined
  86.  
  87. get :: String -> DBOp Connection [String]
  88. get = undefined
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement