{-# LANGUAGE TemplateHaskell, NoMonomorphismRestriction, DeriveFunctor #-} import Control.Lens hiding ( Empty, _Empty ) import Data.Semigroup import Control.Applicative import Control.Monad data Person = Person { _eid :: Int , _name :: String } deriving Show data Project = Project { _lead :: Person , _techLead :: Person } deriving Show data Team = Team { _job1 :: Project , _job2 :: Project } deriving Show makeLenses ''Person makeLenses ''Project makeLenses ''Team myTeam = Team (Project (Person 123 "Pepa") (Person 456 "Franta")) (Project (Person 789 "Lojza") (Person 66 "Sheev")) -- ---------------------------------------------------------------------------- -- Binary trees data BinTree a = Empty | Node { _val :: a , _l :: BinTree a , _r :: BinTree a } deriving (Show, Eq, Ord, Functor) makeLenses ''BinTree -- makePrisms ''BinTree -- Hint: val === _Node . _1, l === _Node . _2, r === _Node . _3 -- Simple testing tree tree1 = Node (4, "koren") (Node (3, "levy") Empty (Node (4, "foo") Empty Empty)) (Node (5, "pravy") (Node (6, "bar") (Node (7, "kia") Empty Empty) (Empty)) (Node (8, "") Empty Empty)) -- Specialisations of the tree above tree1i :: BinTree (Int, String) tree1i = tree1 tree1s :: BinTree (Sum Int, String) tree1s = tree1 -- Dummy effectful updater printVisitor :: Show a => a -> IO a printVisitor x = print x >> return x -- BinTree “pretty” printer ptree :: Show a => BinTree a -> IO () ptree = go 0 where go n Empty = printTreeLine n "." go n (Node v l r) = do printTreeLine n (show v) let n' = succ n go n' l go n' r printTreeLine n x = putStrLn $ n `stimes` " " ++ x -- Generate perfect full binary tree of given depth gentree :: Num a => Int -> BinTree a gentree = go 1 where go _ 0 = Empty go n d = Node n (go (n * 2) d') (go (n * 2 + 1) d') where d' = pred d -- Instances for BinTree. You do not need to worry about this, just know that -- you can use 'traverse' to “focus” on all values of a tree. instance Foldable BinTree where foldr _ z Empty = z foldr f z (Node v l r) = f v (foldr f (foldr f z r) l) instance Traversable BinTree where traverse f Empty = pure Empty traverse f (Node v l r) = liftA3 Node (f v) (traverse f l) (traverse f r)