haskell 中的实例显示树

Instance show tree in haskell

我想为我的二叉树实例化 show 函数,以这种方式构造:data Tree a = Nil | Leaf a | Branch a (Tree a) (Tree a)。 我想实现像 "tree" unix 命令这样的表示。例如:

显示函数为:

> 27
>> 14
>>> 10

>>> 19

>> 35
>>> 31

>>> 42

我想用递归函数将每个 "subtree" 制表,但我不知道这是我的实际代码:

instance (Show a)=>Show (Tree a) where
show Nil = ""
show (Leaf e) = show e
show (Branch e ls rs) = show e ++ "\n\t" ++ show ls ++ "\n\t" ++ show rs

所以问题是:我怎样才能实现递归制表功能,因为每次我只使用换行和制表一次而不是子树深度

你可以定义一个辅助函数,我们这样称呼它showWithDepth:

showWithDepth :: (Show a) => Tree a -> Int -> String
showWithDepth Nil _ = ""
showWithDepth (Leaf e) depth = (replicate depth '\t') ++ show e ++ "\n"
showWithDepth (Branch e ls rs) depth = (replicate depth '\t') ++ show e ++ "\n" ++ showWithDepth ls (depth+1) ++ showWithDepth rs (depth+1)

现在我们可以像这样简单地定义您的实例:

instance (Show a)=>Show (Tree a) where
show x = showWithDepth x 0