【问题标题】:Finding the height寻找高度
【发布时间】:2019-10-02 15:40:03
【问题描述】:

我有以下数据类型

data Tree a -> Node a [Tree a]

并且想找到所有节点的标签和树的高度。

这是我所做的:

height:: Tree a -> Integer height

 (Node _ (x:xs)) = 1 + maximum height' (x:xs)
 height' (x:xs) = map height (x:xs)

我希望 height' 会返回映射到 x:xs 上的高度列表并尝试找到该值的最大值,但 ghci 不同意这里的 map 函数。

【问题讨论】:

  • “失败,因为 xs 是一个树列表,而不是函数类型签名所指示的单个树” - 那么为什么要将 labels 应用于列表 xs?你想把它应用到这个列表的每个元素上,而真正做到这一点的函数是......?您也不需要在`labels 中将xxs 分开。
  • 因为我不确定如何应用到列表中的每个元素而不是整个列表..
  • 你快到了。你应该在你的列表中map这个函数:labels (Node label children) = label : (map labels children)
  • 我之前尝试过这样做,但收到错误消息:Occurs check: cannot construct the infinite type: a ~ [a] Expected type: [a] Actual type: [[a]]
  • 我建议你在另一个问题中添加标签功能,全栈错误

标签: list haskell tree


【解决方案1】:

您可以将其写在一行中:

height :: Integral i => Tree a -> i
height (Node _ cs) = 1 + maximum (0 : map height cs)

对于每个节点,我们因此返回1 + …,其中0 的最大值以及这些节点的子节点的高度。我们在这里使用0 来防止这种情况,如果Node 没有孩子,maximum 将处理一个空列表,从而引发错误。

【讨论】:

    【解决方案2】:

    考虑到我将树定义为:

    data GenTree a = NodeG a [GenTree a] deriving (Show)
    

    好吧,在这个你离你更近一点的地方:

    height:: GenTree a -> Integer
    height (NodeG _ [])    = 0 -- Deep 0
    height (NodeG _ trees) = 1 + (maximum $ heightLs trees) -- take the max
    
    -- (maximum $ heightLs trees) == (maximum (heightLs trees))
    
    heightLs (x:xs) = map height (x:xs) -- here is perfect
    
    genTree1 = NodeG "1" [NodeG "2" [],
                             NodeG "3" [NodeG "4" [],
                                       NodeG "5" [NodeG "6" [],
                                                 NodeG "7" [],
                                                 NodeG "8" [
                                                            NodeG "9" []
                                                            ]
                                                 ]
                                       ]
                             ]
    

    例子

    $>   height genTree1
    => 4
    

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2021-09-18
      • 1970-01-01
      • 2016-03-26
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多