Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
74
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.  
  3. data Pair a = P a a deriving (Show, Eq)
  4.  
  5. true, false :: Pair a -> a
  6. true (P a _) = a
  7. false (P _ b) = b
  8.  
  9. instance Monad Pair where
  10. return x = P x x
  11. P a b >>= f = P (true $ f a) (false $ f b)
  12.  
  13.  
  14. -- GS is a monad
  15. --
  16. data GS a = GS { unGS :: Pair [a] } deriving (Show, Eq)
  17.  
  18. instance Monad GS where
  19. return = GS . return . return
  20. GS pair >>= f = GS $ do xs <- pair
  21. P (concat [true . unGS . f $ x | x <- xs])
  22. (concat [false . unGS . f $ x | x <- xs])
  23.  
  24.  
  25. -- SG isn't a monad
  26. --
  27. data SG a = SG { unSG :: [Pair a] } deriving (Show, Eq)
  28.  
  29. returnSG :: a -> SG a
  30. returnSG x = SG [P x x]
  31.  
  32. (>>>=) :: Eq b => SG a -> (a -> SG b) -> SG b
  33. SG sgx >>>= f = SG $ fmap join . join $ sequence <$> (fmap (unSG . f) <$> sgx)
  34.  
  35. main = print $ returnSG 0 >>>= \x -> SG $ [return x] ++ [return 1]
  36.  
  37.  
  38. -- BTW this doesn't help
  39. --
  40. sequenceX :: (Eq a, MonadPlus m) => Pair (m a) -> m (Pair a)
  41. sequenceX (P ma mb) = do a <- ma
  42. b <- mb
  43. if a == b then return $ P a b else mzero
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51. {- crufty boilerplate -}
  52.  
  53. instance Applicative Pair where
  54. pure = return
  55. ff <*> xx = do f <- ff
  56. x <- xx
  57. return $ f x
  58.  
  59. instance Functor Pair where
  60. fmap f xx = pure f <*> xx
  61.  
  62. instance Foldable Pair where
  63. foldr f z (P a b) = f a $ f b z
  64.  
  65. instance Traversable Pair where
  66. traverse f (P a b) = P <$> f a <*> f b
  67.  
  68. instance Applicative GS where
  69. pure = return
  70. ff <*> xx = do f <- ff
  71. x <- xx
  72. return $ f x
  73.  
  74. instance Functor GS where
  75. fmap f xx = pure f <*> xx
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement