data Tree a = Leaf (a) | Bin (Tree a) (Tree a) deriving (Show) main :: IO () main = print (t1, depth t1) t1 :: Tree Char t1 = balance "Patrik" depth :: Tree a -> Int depth = cata_f4Tree de balance :: [a] -> Tree a balance = ana_f4Tree ba cata_f4Tree :: (Either a (b, b) -> b) -> Tree a -> b cata_f4Tree i = i . ((fmap2_f4Tree id (cata_f4Tree i)) . out_f4Tree) de :: Either a (Int, Int) -> Int de = either (const 0) (\(m, n) -> 1 + (max m n)) ana_f4Tree :: (a -> Either b (a, a)) -> a -> Tree b ana_f4Tree o = inn_f4Tree . ((fmap2_f4Tree id (ana_f4Tree o)) . o) ba :: [a] -> Either a ([a], [a]) ba xs = case xs of ([]) -> error "Can't represent the empty list" (x : ([])) -> Left x xs -> Right (splitAt (div (length xs) 2) xs) fmap2_f4Tree :: (a -> b) -> (c -> d) -> Either a (c, c) -> Either b (d, d) fmap2_f4Tree = \p r -> (fmap2_p p r) -+- (fmap2_Prr p r) out_f4Tree :: Tree a -> Either a (Tree a, Tree a) out_f4Tree x = case x of (Leaf a) -> Left a (Bin a b) -> Right (a, b) inn_f4Tree :: Either a (Tree a, Tree a) -> Tree a inn_f4Tree = either Leaf (uncurry Bin) (-+-) :: (a -> b) -> (c -> d) -> Either a c -> Either b d f -+- g = either (Left . f) (Right . g) fmap2_p :: (a -> b) -> (c -> d) -> a -> b fmap2_p = \p r -> p fmap2_Prr :: (a -> b) -> (c -> d) -> (c, c) -> (d, d) fmap2_Prr = \p r -> (fmap2_r p r) -*- (fmap2_r p r) (-*-) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) f -*- g = \(x, y) -> (f x, g y) fmap2_r :: (a -> b) -> (c -> d) -> c -> d fmap2_r = \p r -> r