標籤:
上節介紹了泛函資料結構List及相關的泛函編程函數設計使用,還附帶了少許多態類型(Polymorphic Type)及變形(Type Variance)的介紹。有關Polymorphism的詳細介紹會放在typeclass討論中。為了更多瞭解泛函資料結構(Functional Data Structure),想在這個章節把另一個我們熟悉的資料結構-Tree做些簡單介紹。
Tree的狀態不是枝(Branch)就是葉(Leaf),這個很容易理解。那麼就按照上節設計List那樣設計Tree類型:
1 trait Tree[+A] 2 case class Leaf[A](value: A) extends Tree[A]3 case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
類參數+A代表協變(covariant),這個在上節List中已經介紹過了。先建立一個Tree執行個體(Tree Instance):
1 val tree = Branch(Branch(Leaf(1),Leaf(2)),Branch(Branch(Leaf(10),Leaf(8)),Leaf(3)))2 //> tree : ch3.tree.Branch[Int] = Branch(Branch(Leaf(1),Leaf(2)),Branch(Branch(3 //| Leaf(10),Leaf(8)),Leaf(3)))
建立了一個Tree Instance tree,如:
數數有幾個節點:
1 def size: Int = this match {2 case Leaf(_) => 13 case Branch(l,r) => 1 + l.size + r.size4 }
1 tree size //> res0: Int = 9
這是所有branch + leaf 總數。
分開計算branch 和 leaf 數量:
1 def countLeafs: Int = this match {2 case Leaf(_) => 13 case Branch(l,r) => 0 + l.size + r.size4 }5 def countBranches: Int = this match {6 case Leaf(_) => 07 case Branch(l,r) => 1 + l.size + r.size8 }9
1 tree.countLeafs //> res1: Int = 82 tree.countBranches //> res2: Int = 9
探探最深有多深:
1 def depth: Int = this match {2 case Leaf(_) => 03 case Branch(l,r) => 1 + (l.depth max r.depth)4 }
1 tree depth //> res1: Int = 3
找出最大值的Leaf:
1 def maxValue: Int = this match {2 case Leaf(a: Int) => a3 case Branch(l,r) => l.maxValue max r.maxValue4 }
1 tree maxValue //> res2: Int = 10
可以從以上這些函數得出一下共性。把共性抽象出來用fold來實現:
1 def fold[B](f: A => B)(g: (B,B) => B): B = this match {2 case Leaf(n) => f(n)3 case Branch(l,r) => g(l.fold(f)(g), r.fold(f)(g))4 }
函數fold分別收到兩個方法f,g:f用來處理Leaf,g用來處理Branch。看看用fold來實現上面的函數:
1 def sizeByfold = fold(a => 1)(1 + _ + _)2 def maxValueByfold(l: Tree[Int]) = l.fold(a => a)((x,y) => 0 + (x max y))3 def depthByfold = fold(a => 0)((x,y) => 1 + (x max y))
1 tree sizeByfold //> res3: Int = 92 3 tree depthByfold //> res4: Int = 34 5 tree.maxValueByfold(tree) //> res5: Int = 10
可能這個 tree.maxValueByfold(tree) 有點怪,但如果把函數實現放到 object Tree裡然後import Tree._就可以了。
下面把map和flatMap實現了:
1 def map[B](f: A => B): Tree[B] = this match {2 case Leaf(a) => Leaf(f(a))3 case Branch(l,r) => Branch(l.map(f),r.map(f))4 }5 def flatMap[B](f: A => Tree[B]): Tree[B] = this match {6 case Leaf(a) => f(a)7 case Branch(l,r) => Branch(l.flatMap(f), r.flatMap(f))8 }
泛函編程(8)-資料結構-Tree