[英]Height of a Rose Tree Haskell
Consider the following definition of Rose Trees:考虑以下玫瑰树的定义:
data RTree a = R a [RTree a]
I need help defining the function rtHeight :: (RTree a) -> Int
that calculates the height of a rose tree.我需要帮助定义函数
rtHeight :: (RTree a) -> Int
来计算玫瑰树的高度。
So far, I have tried the following到目前为止,我已经尝试了以下
rtHeight R a [] = 1
rtHeight R a l = 1 + rtHeight l
However, this does not work becuase l is a list of rose trees.但是,这不起作用,因为 l 是玫瑰树的列表。 I have also tried the following:
我还尝试了以下方法:
rtHeight R a [] = 1
rtHeight R a l = maximum (map (rtHeight) l)
I believe this fails becuase I am not adding a level while I am going down the tree.我相信这会失败,因为我在下树时没有添加关卡。
In Why Functional Programming Matters (PDF) , the author includes a code that is equivalent to the following:在Why Functional Programming Matters (PDF) 中,作者包含了一段等效于以下内容的代码:
reduce_tree f g z t =
f (label t) (reduce (g . reduce_tree f g z) z (branches t))
Using it, we can write使用它,我们可以写
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
As an illustration, for a tree t = R a [b,c,d]
, this calculates t
's height as例如,对于一棵树
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))
That is because, for the built-in foldr
function ,那是因为,对于内置的
foldr
函数,
foldr g z [a,b,c,...,n] == g a (g b (g c (... (g n z)...)))
An interesting identity is foldr (g . h) z xs == foldr gz (map h xs)
, and since maximum (xs ++ [0]) == foldr max 0 xs
, your direct recursive formulation of rtHeight
can be recovered from this generalized formulation.一个有趣的身份是
foldr (g . h) z xs == foldr gz (map h xs)
,并且由于maximum (xs ++ [0]) == foldr max 0 xs
,您的rtHeight
直接递归公式可以从这种广义的表述。
Here is my final answer.这是我的最终答案。 Tested and it worked:
经过测试,它有效:
rtHeight R a [] = 1
rtHeight R a l = 1 + maximum (map (rtHeight) l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.