Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. {-# LANGUAGE RankNTypes #-}
  2. import Data.Monoid
  3.  
  4. class Buildable f where
  5. build :: (forall m. Monoid m => (a -> m) -> m) -> f a
  6.  
  7. -- foldMap f (build g) = g f
  8. -- build (\f -> foldMap f x) = x
  9.  
  10. instance Buildable [] where
  11. build f = appEndo (f (Endo . (:))) []
  12. -- instance Buildable FMList where
  13. -- build = FM
  14.  
  15. transform :: (Foldable f1, Buildable f2) => (forall m. Monoid m => (b -> m) -> (a -> m)) -> f1 a -> f2 b
  16. transform f as = build (\g -> foldMap (f g) as)
  17.  
  18. fromFoldable :: (Foldable f, Buildable t) => f a -> t a
  19. fromFoldable = transform id
  20. fmapDefault f = transform (. f)
  21. singleton a = build (\f -> f a)
  22. memptyDefault :: Buildable f => f a
  23. memptyDefault = build (const mempty) -- == build mempty
  24. mappendDefault l r = build (\f -> foldMap f l <> foldMap f r)
  25. cons a as = build (\f -> f a <> foldMap f as)
  26. snoc as a = build (\f -> foldMap f as <> f a)
  27. rev as = build (\f -> getDual $ foldMap (Dual . f) as)
  28. flatten :: (Foldable f, Buildable f, Foldable g) => f (g a) -> f a
  29. flatten = transform foldMap
  30. filter p = transform (\f a -> if p a then f a else mempty)
  31. unfold :: (Foldable f, Buildable t) => (b -> f (Either b a)) -> b -> t a
  32. unfold g b = build (\f -> let go = foldMap (either go f) . g in go b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement