Kapitel 6: Programmiertechniken hugs Show ghc -c Show.lhs > module Show > where > data Tree lab = Empty | Node (Tree lab) lab (Tree lab) > showTree1 :: (Show a) => Tree a -> String > showTree1 Empty = "Empty" > showTree1 (Node l a r) = "(Node " > ++ showTree1 l ++ " " > ++ show a ++ " " > ++ showTree1 r ++ ")" > lefty :: Int -> Tree Int > lefty 0 = Empty > lefty (n + 1) = Node (lefty n) n Empty < showsTree t x = showTree t ++ x -- Spezifikation > showsTree2 :: (Show a) => Tree a -> String -> String > showsTree2 Empty x = "Empty" ++ x > showsTree2 (Node l a r) x = "(Node " > ++ showsTree2 l (" " > ++ shows a (" " > ++ showsTree2 r (")" ++ x))) > showTree2 :: (Show a) => Tree a -> String > showTree2 t = showsTree2 t "" < type ShowS = String -> String > showsTree3 :: (Show a) => Tree a -> ShowS > showsTree3 Empty = showString "Empty" > showsTree3 (Node l a r) = showString "(Node " > . showsTree3 l . showChar ' ' > . shows a . showChar ' ' > . showsTree3 r . showChar ')' < showChar = (:) < showString = (++) > showTree3 :: (Show a) => Tree a -> String > showTree3 t = showsTreePrec 0 t "" > showsTreePrec :: (Show a) => Int -> Tree a -> ShowS > showsTreePrec d Empty = showString "Empty" > showsTreePrec d (Node l a r) = showParen (d >= 10) ( > showString "Node " > . showsTreePrec 10 l . showChar ' ' > . showsPrec 10 a . showChar ' ' > . showsTreePrec 10 r) < showParen :: Bool -> ShowS -> ShowS < showParen False p = p < showParen True p = showChar '(' . p . showChar ')' < class Show a where < show :: a -> String < showsPrec :: Int -> a -> ShowS < showList :: [a] -> ShowS < < showsPrec _ x s = show x ++ s < < show x = showsPrec 0 x "" < < showList [] = showString "[]" < showList (x : xs) = showChar '[' . shows x . showl xs < where showl [] = showChar ']' < showl (x : xs) = showChar ',' . shows x . showl xs > instance (Show a) => Show (Tree a) where > showsPrec d Empty = showString "Empty" > showsPrec d (Node l a r) = showParen (d >= 10) ( > showString "Node " > . showsPrec 10 l . showChar ' ' > . showsPrec 10 a . showChar ' ' > . showsPrec 10 r)