我已经编写了这段代码来打印一张树:
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)
示例输出:
*Main> putStr $ printTree $ Tree A [Tree A [A,B,C], C]
A
A
A
B
C
C
现在我想将此作为show
的实现。这种方法很接近,但我找不到一种方法来调用内置的show
:
instance Show Node where
show (Tree node children) = printTree (Tree node children)
show _ = "node... can I call the built-in show here?"
(在这个例子中,我可以处理A,B和C.但是在实际代码中,有许多节点类型。)
答案 0 :(得分:8)
我能看到的唯一方法就是分成两种类型。
data Tree node = Tree node [Tree node]
data Node = A | B | C deriving Show
instance Show node => Show (Tree node) where ....
答案 1 :(得分:1)
遵循MathematicalOrchid的回应,最好的方法是使用新类型,但这是组织类型的更好方法:
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