Advertisement
ulysses4ever

Deriving Functor and Foldable, use existensial wrapper

Nov 6th, 2015
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE DeriveTraversable, ExistentialQuantification #-}
  2.  
  3. data Tree a
  4.     = L a        -- Leaf holds data
  5.     | N [Tree a] -- Node holds list of trees
  6.     deriving (Functor, Foldable, Traversable, Show)
  7.  
  8. aTree :: Tree Int
  9. aTree
  10.     = N
  11.         [ L 5
  12.         , N
  13.             [ L 42
  14.             , L 41
  15.             ]
  16.         , L 7
  17.         ]
  18.  
  19. data Showable = forall a. Show a => Sh a
  20.  
  21. instance Show Showable where
  22.   show (Sh a) = show a
  23.  
  24. -- deadly want to get rid of `Sh .`-boilerplate
  25. actions :: [Tree Int -> Showable]
  26. actions = [Sh . sum, Sh . fmap (+ 1)] -- and many more...
  27.  
  28. main :: IO ()
  29. main = print $ map ($ aTree) actions  -- => [95,N [L 6,N [L 43,L 42],L 8]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement