【问题标题】:Instance show tree in haskellHaskell 中的实例展示树
【发布时间】:2018-05-26 17:10:18
【问题描述】:

我想为我的二叉树实例化显示函数,以这种方式构造:data Tree a = Nil | Leaf a | Branch a (Tree a) (Tree a)。 我想实现像“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

所以问题是:我如何实现递归制表函数,因为每次我使用换行和制表一次而不是子树深度

【问题讨论】:

    标签: haskell tree instance show


    【解决方案1】:

    您可以定义一个辅助函数,我们将其称为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
    

    【讨论】:

    • 如果你复制'\t'而不是"\t",则不需要concat
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多