我编写了这段代码来漂亮地打印一棵树:
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。但在实际代码中,有很多节点类型。)
最佳答案
我认为做到这一点的唯一方法是将其分为两种类型。
data Tree node = Tree node [Tree node]
data Node = A | B | C deriving Show
instance Show node => Show (Tree node) where ....
关于haskell - 我可以部分导出 Show 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31249175/