Haskell语言学习笔记(76)Data.Tree
程序员文章站
2022-03-01 15:44:56
...
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
Prelude Data.Tree> tree = Node "A" [Node "B" [], Node "C" [Node "D" [], Node "E" []]]
Prelude Data.Tree> print tree
Node {rootLabel = "A", subForest = [Node {rootLabel = "B", subForest = []},Node {rootLabel = "C", subForest = [Node {rootLabel = "D", subForest = []},Node {rootLabel = "E", subForest = []}]}]}
Prelude Data.Tree> putStr $ drawTree tree
A
|
+- B
|
`- C
|
+- D
|
`- E
Prelude Data.Tree> putStr $ drawForest $ subForest tree
B
C
|
+- D
|
`- E
Prelude Data.Tree> flatten tree
["A","B","C","D","E"]
Prelude Data.Tree> levels tree
[["A"],["B","C"],["D","E"]]
实例
推荐阅读
-
Java语言Consistent Hash算法学习笔记(代码示例)
-
Java语言Consistent Hash算法学习笔记(代码示例)
-
go 语言学习笔记
-
Go 语言的指针的学习笔记
-
Java语言Consistent Hash算法学习笔记(代码示例)
-
C语言学习笔记—code:blocks工具debug调试异常
-
oracle学习笔记(三) DCL 数据控制语言与 DDL 数据定义语言
-
【学习笔记】C语言习题:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
-
[python学习笔记]Python语言程序设计(北理工 嵩天)
-
Go语言学习笔记(1)——Hello World!