Is it possible to partially show Show?

I wrote this code for a beautiful tree print:

data Node = A | B | C | Tree Node [Node] deriving (Show, Eq) printTree' :: Int -> Node -> [String] printTree' spaceCount (Tree node children) = (printTree' spaceCount node) ++ concat (map (\child -> printTree' (spaceCount+2) child) children) printTree' spaceCount leaf = [(replicate spaceCount ' ') ++ (show leaf)] printTree :: Node -> String printTree node = unlines (printTree' 0 node) 

Output Example:

 *Main> putStr $ printTree $ Tree A [Tree A [A,B,C], C] A A A B C C 

Now I would like to do this for the implementation of show . This approach is close, but I cannot find a way to invoke the built-in show :

 instance Show Node where show (Tree node children) = printTree (Tree node children) show _ = "node... can I call the built-in show here?" 

(In this example, I can just deal with A, B, and C. But in the real code, there are many types of node.)

+5
source share
2 answers

The only way I can do this is to split into two types.

 data Tree node = Tree node [Tree node] data Node = A | B | C deriving Show instance Show node => Show (Tree node) where .... 
+8
source

Following the answer to the mathematical orchid, the best way to do this is a new type, but here is the best way to organize the types:

 data Node = Leaf Leaf | Tree Node [Node] deriving Eq data Leaf = A | B | C deriving (Eq, Show) instance Show Node where show (Tree node children) = printTree (Tree node children) show (Leaf l) = show l 
+1
source

All Articles