首页 > 编程语言 > 详细

Haskell语言学习笔记(76)Data.Tree

时间:2018-06-30 18:33:14      阅读:207      评论:0      收藏:0      [点我收藏+]

Data.Tree

data Tree a = Node {
        rootLabel :: a,
        subForest :: Forest a
    } deriving (Eq, Read, Show)
type Forest a = [Tree a]

Data.Tree 是一种非空(存在根节点),可以有无限分支,每个节点均可有多路分支的Tree类型。

Prelude Data.Tree> :t Node 1
Node 1 :: Num a => Forest a -> Tree a
Prelude Data.Tree> a = Node 1 [Node 2 [], Node 3 []]
Prelude Data.Tree> a
Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []},Node {rootLabel = 3, subForest = []}]}
Prelude Data.Tree> putStr $ drawTree $ fmap show a
1
|
+- 2
|
`- 3
Prelude Data.Tree> foldTree (\x xs -> sum (x:xs)) a
6
Prelude Data.Tree> foldTree (\x xs -> maximum (x:xs)) a
3

实例

import Data.Tree

tree = Node "A" [Node "B" [], Node "C" [Node "D" [], Node "E" []]]

main = do
    print tree
    putStrLn $ drawTree tree
    putStrLn $ drawForest $ subForest tree

    print $ flatten tree
    print $ levels tree
Node {rootLabel = "A", subForest = [Node {rootLabel = "B", subForest = []},Node {rootLabel = "C", subForest = [Node {rootLabel = "D", subForest = []},Node {rootLabel = "E", subForest = []}]}]}
A
|
+- B
|
`- C
   |
   +- D
   |
   `- E

B

C
|

+- D
|
`- E


["A","B","C","D","E"]
[["A"],["B","C"],["D","E"]]

Haskell语言学习笔记(76)Data.Tree

原文:https://www.cnblogs.com/zwvista/p/9248182.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!