Guest User

Untitled

a guest
Jan 21st, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. {--
  2. Goal of this exercise is to show most common typeclasses and their usages.
  3. Requires base >= 4.11
  4. --}
  5.  
  6.  
  7.  
  8. data List a
  9. = MkEmpty
  10. | MkCons a (List a)
  11.  
  12. instance Semigroup (List a) where
  13. -- :: List a -> List a -> List a
  14. MkEmpty <> ys = ys
  15. (MkCons x xs) <> ys = MkCons x (xs `mappend` ys)
  16.  
  17. instance Monoid (List a) where
  18. mempty = MkEmpty
  19.  
  20. instance Functor List where
  21. -- :: (a -> b) -> List a -> List b
  22. fmap _ MkEmpty = MkEmpty
  23. fmap fn (MkCons x xs) = fn x `MkCons` fmap fn xs
  24.  
  25. instance Applicative List where
  26. -- :: a -> List a
  27. pure x = MkCons x MkEmpty
  28. -- :: f (a -> b) -> f a -> f b
  29. fs <*> xs = joinL $ fmap (\f -> fmap f xs) fs
  30.  
  31. instance Monad List where
  32. --
  33. return = pure
  34. --
  35. xs >>= fn = foldr joinL $ fmap fn xs
  36.  
  37. instance Foldable List where
  38. -- :: (a -> b -> b) -> b -> t a -> b
  39. foldr _ init MkEmpty = init
  40. foldr fn init (MkCons x xs) = fn x $ foldr fn init xs
  41.  
  42. instance Traversable List where
  43. -- :: Applicative f => (a -> f b) -> List a -> f (List b)
  44. traverse _ MkEmpty = pure MkEmpty
  45. traverse fn (MkCons x xs) = pure MkCons <*> fn x <*> traverse fn xs
  46.  
  47. instance (Show a) => Show (List a) where
  48. show = ("list"++) . show . toLs
  49.  
  50. joinL :: List (List a) -> List a
  51. joinL = foldr (<>) mempty
  52.  
  53. {--
  54. --}
  55. toLs :: List a -> [a]
  56. toLs = foldr (:) []
  57.  
  58. fromLs :: [a] -> List a
  59. fromLs = foldr MkCons MkEmpty
  60.  
  61. main = do
  62. print $ fromLs [1,2,3]
  63. print $ toLs $ fromLs [1,2,3]
  64. print $ traverse (\x -> Just x) $ fromLs [1,2,3]
  65. print $ fromLs [(+1), (+2)] <*> fromLs [10, 20]
  66. print $ do
  67. x <- fromLs [1, 2]
  68. y <- fromLs "abc"
  69. return (x, y)
Add Comment
Please, Sign In to add comment