我希望实例显示我的二叉树的功能,以这种方式构建:data Tree a = Nil | Leaf a | Branch a (Tree a) (Tree a)
。
我希望获得像#tree; tree" unix命令。例如:
显示功能如下:
> 27
>> 14
>>> 10
>>> 19
>> 35
>>> 31
>>> 42
我想列出每个"子树"具有递归功能但我不知道这是我的实际代码:
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
所以问题是:我如何实现递归制表功能,因为每次我使用新行并仅制表一次而不是子树深度
答案 0 :(得分:2)
你可以定义一个辅助函数,我们这样称它为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