我有一个树数据类型:
data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a
...我需要使它成为一个实例Show
,不使用deriving
。我发现很好地显示带有两片叶子的小树枝很容易:
instance (Show a, Show b) => Show (Tree a b) where
show (Leaf x) = show x
show (Branch val l r) = " " ++ show val ++ "\n" ++ show l ++ " " ++ show r
但是如何将一个好的结构扩展到任意大小的树呢?似乎确定间距需要我知道最底部有多少叶子(或者总共有多少叶子),以便我可以在那里分配我需要的所有空间并进行工作。 '我可能需要调用一个大小函数。我认为这是可行的,但这是否会让事情变得更加困难?
你可能会研究drawTree http://hackage.haskell.org/package/containers-0.5.7.1/docs/src/Data.Tree.html#drawTree基地内的功能Data.Tree http://hackage.haskell.org/packages/archive/containers/0.3.0.0/doc/html/src/Data-Tree.html模块。只是无耻地导入它会给你这样的东西:
import Data.Tree hiding (Tree )
data Tree a b = Branch b (Tree a b) (Tree a b)
| Leaf a deriving (Eq,Ord,Show)
toDataTree (Leaf a) = Node a []
toDataTree (Branch b cs ds) = Node b [toDataTree cs, toDataTree ds]
d = Branch "1" (Branch "11" (Leaf "111") (Leaf "112"))
(Branch "12" (Leaf "121") (Leaf "122"))
e = toDataTree d
f = putStrLn $ drawTree e
{-
*Main> f
1
|
+- 11
| |
| +- 111
| |
| `- 112
|
`- 12
|
+- 121
|
`- 122
-}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)