考虑显示树哈斯克尔
data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a
我试图定义显示的一个实例(没有导入任何模块或使用派生),这将显示树形像这样
Main*> let a = Branch "x" (Branch "y" (Leaf 4) (Leaf 7)) (Leaf 9)
Main*> a
"x"
"y"
4
7
9
以下数据类型
到目前为止,这是我想出的
findDepth (Leaf a) = 0
findDepth (Branch a (b) (c)) = 1 + (max (findDepth b) (findDepth c))
data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a
instance (Show a, Show b) => Show (Tree a b) where
show (Leaf x) = show x
show (Branch a (b) (c)) =
show a ++ "\n" ++ s2 ++ show b ++ "\n" ++ s2 ++ show C++ "\n" ++ s1
where
d = findDepth (Branch a (b) (c))
s1 = addSpace (d-1)
s2 = addSpace d
addSpace n = replicate n '\t'
不幸的是,这使得节点h最深,最深的节点最少。我知道findDepth函数实际上应该给叶子最大的价值和分支最低价值,但不能找出一种方法来递归地为这两个参数编写函数。有什么建议么?
如果您不认为这是其他问题的重复,请随时添加注释(不要忘记添加'@ Zeta')。这就是说,你仍然可以接受一个已发布的答案。顺便说一句,目前是否有某种Haskell讲座?一些最新的问题非常相似。 – Zeta