玫瑰树Haskell的高度

时间:2014-02-09 00:10:58

标签: haskell tree numbers height

考虑玫瑰树的以下定义:

data RTree a = R a [RTree a]

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

2 个答案:

答案 0 :(得分:2)

Why Functional Programming Matters (PDF)中,作者包含的代码与以下代码相同:

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
    label    (R a _ ) = a
    branches (R _ bs) = bs
    reduce = foldr
    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

例如,对于树t = R a [b,c,d],这会将t的高度计算为

rtHeight t = 1 + max (rtHeight b)         -- rtHeight == reduce_tree f g z
                     (max (rtHeight c)
                          (max (rtHeight d)
                               0))

这是因为,对于内置的foldr function

foldr g z [a,b,c,...,n] == g a (g b (g c (... (g n z)...)))

一个有趣的身份是foldr (g . h) z xs == foldr g z (map h xs),从maximum (xs ++ [0]) == foldr max 0 xs开始,rtHeight的直接递归式可以从这个通用的公式中找到。

答案 1 :(得分:2)

这是我的最终答案。经过测试并且有效:

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