玫瑰树的高度Haskell

玫瑰树的高度Haskell,haskell,tree,numbers,height,Haskell,Tree,Numbers,Height,考虑以下玫瑰树的定义: data RTree a = R a [RTree a] 我需要帮助定义计算玫瑰树高度的函数rtHeight::(rtreea)->Int 到目前为止,我已经尝试了以下方法 rtHeight R a [] = 1 rtHeight R a l = 1 + rtHeight l 但是,这不起作用,因为l是玫瑰树列表。 我还尝试了以下方法: rtHeight R a [] = 1 rtHeight R a l = maximum (map (rtHeight) l) r

考虑以下玫瑰树的定义:

data RTree a = R a [RTree a]
我需要帮助定义计算玫瑰树高度的函数
rtHeight::(rtreea)->Int

到目前为止,我已经尝试了以下方法

rtHeight R a [] = 1
rtHeight R a l = 1 + rtHeight l
但是,这不起作用,因为l是玫瑰树列表。 我还尝试了以下方法:

rtHeight R a [] = 1
rtHeight R a l = maximum (map (rtHeight) l)
reduce_tree f g z t =
  f (label t) (reduce (g . reduce_tree f g z) z (branches t))
我相信这是失败的,因为我没有在树下添加关卡。

在中,作者包含了一个代码,相当于以下代码:

rtHeight R a [] = 1
rtHeight R a l = maximum (map (rtHeight) l)
reduce_tree f g z t =
  f (label t) (reduce (g . reduce_tree f g z) z (branches t))
使用它,我们可以写作

rtHeight t = reduce_tree f g z t
  where
    f _ y  = 1 + y      -- 1 more than maximum height of subtrees
    g x y  = max x y    -- y is maximum height of subtrees to the right
    z      = 0          -- the smallest height is 0

label    (R a _ ) = a
branches (R _ bs) = bs
reduce = foldr
举例来说,对于一棵树,
t=ra[b,c,d]
,它将
t
的高度计算为

rtHeight t = 1 + max (rtHeight b)         -- rtHeight == reduce_tree f g z
                     (max (rtHeight c)
                          (max (rtHeight d)
                               0))
那是因为,对于内置的

一个有趣的恒等式是
foldr(g.h)zxs==foldr gz(map hxs)
,由于
maximum(xs++[0])==foldr max 0xs
,您的
rtHeight
的直接递归公式可以从这个广义公式中恢复。

在中,作者包含了一个相当于以下内容的代码:

rtHeight R a [] = 1
rtHeight R a l = maximum (map (rtHeight) l)
reduce_tree f g z t =
  f (label t) (reduce (g . reduce_tree f g z) z (branches t))
使用它,我们可以写作

rtHeight t = reduce_tree f g z t
  where
    f _ y  = 1 + y      -- 1 more than maximum height of subtrees
    g x y  = max x y    -- y is maximum height of subtrees to the right
    z      = 0          -- the smallest height is 0

label    (R a _ ) = a
branches (R _ bs) = bs
reduce = foldr
举例来说,对于一棵树,
t=ra[b,c,d]
,它将
t
的高度计算为

rtHeight t = 1 + max (rtHeight b)         -- rtHeight == reduce_tree f g z
                     (max (rtHeight c)
                          (max (rtHeight d)
                               0))
那是因为,对于内置的


一个有趣的恒等式是
foldr(g.h)zxs==foldr gz(map hxs)
,由于
max(xs++[0])==foldr max 0xs
,您的
rtHeight
的直接递归公式可以从这个广义公式中恢复。

这是我的最终答案。经过测试,效果良好:

rtHeight R a [] = 1
rtHeight R a l = 1 + maximum (map (rtHeight) l)

这是我最后的答案。经过测试,效果良好:

rtHeight R a [] = 1
rtHeight R a l = 1 + maximum (map (rtHeight) l)

你太近了!只需混合和匹配:从一个添加级别的解决方案中获取位,从另一个处理列表的解决方案中获取位。(别忘了更正括号。)你太接近了!只需混合和匹配:从一个添加级别的解决方案中获取位,从另一个处理列表的解决方案中获取位。(别忘了更正括号。)