泛函编程(8)-数据结构-Tree
上节介绍了泛函数据结构List及相关的泛函编程函数设计使用,还附带了少许多态类型(Polymorphic Type)及变形(Type Variance)的介绍。有关Polymorphism的详细介绍会放在typeclass讨论中。为了更多了解泛函数据结构(Functional Data Structure),想在这个章节把另一个我们熟悉的数据结构-Tree做些简单介绍。
Tree的状态不是枝(Branch)就是叶(Leaf),这个很容易理解。那么就按照上节设计List那样设计Tree类型:
trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
类参数+A代表协变(covariant),这个在上节List中已经介绍过了。先创建一个Tree实例(Tree Instance):
val tree = Branch(Branch(Leaf(1),Leaf(2)),Branch(Branch(Leaf(10),Leaf(8)),Leaf(3)))
//> tree : ch3.tree.Branch[Int] = Branch(Branch(Leaf(1),Leaf(2)),Branch(Branch(
//| Leaf(10),Leaf(8)),Leaf(3)))
创建了一个Tree Instance tree,如下图:
数数有几个节点:
def size: Int = this match {
case Leaf(_) => 1
case Branch(l,r) => 1 + l.size + r.size
}
tree size //> res0: Int = 9
这是所有branch + leaf 总数。
分开计算branch 和 leaf 数量:
def countLeafs: Int = this match {
case Leaf(_) => 1
case Branch(l,r) => 0 + l.size + r.size
}
def countBranches: Int = this match {
case Leaf(_) => 0
case Branch(l,r) => 1 + l.size + r.size
}
tree.countLeafs //> res1: Int = 8
tree.countBranches //> res2: Int = 9
探探最深有多深:
def depth: Int = this match {
case Leaf(_) => 0
case Branch(l,r) => 1 + (l.depth max r.depth)
}
tree depth //> res1: Int = 3
找出最大值的Leaf:
def maxValue: Int = this match {
case Leaf(a: Int) => a
case Branch(l,r) => l.maxValue max r.maxValue
}
tree maxValue //> res2: Int = 10
可以从以上这些函数得出一下共性。把共性抽象出来用fold来实现:
def fold[B](f: A => B)(g: (B,B) => B): B = this match {
case Leaf(n) => f(n)
case Branch(l,r) => g(l.fold(f)(g), r.fold(f)(g))
}
函数fold分别收到两个方法f,g:f用来处理Leaf,g用来处理Branch。看看用fold来实现上面的函数:
def sizeByfold = fold(a => 1)(1 + _ + _)
def maxValueByfold(l: Tree[Int]) = l.fold(a => a)((x,y) => 0 + (x max y))
def depthByfold = fold(a => 0)((x,y) => 1 + (x max y))
tree sizeByfold //> res3: Int = 9 tree depthByfold //> res4: Int = 3 tree.maxValueByfold(tree) //> res5: Int = 10
可能这个 tree.maxValueByfold(tree) 有点怪,但如果把函数实现放到 object Tree里然后import Tree._就可以了。
下面把map和flatMap实现了:
def map[B](f: A => B): Tree[B] = this match {
case Leaf(a) => Leaf(f(a))
case Branch(l,r) => Branch(l.map(f),r.map(f))
}
def flatMap[B](f: A => Tree[B]): Tree[B] = this match {
case Leaf(a) => f(a)
case Branch(l,r) => Branch(l.flatMap(f), r.flatMap(f))
}
泛函编程(8)-数据结构-Tree的更多相关文章
- 泛函编程(5)-数据结构(Functional Data Structures)
编程即是编制对数据进行运算的过程.特殊的运算必须用特定的数据结构来支持有效运算.如果没有数据结构的支持,我们就只能为每条数据申明一个内存地址了,然后使用这些地址来操作这些数据,也就是我们熟悉的申明变量 ...
- 泛函编程(6)-数据结构-List基础
List是一种最普通的泛函数据结构,比较直观,有良好的示范基础.List就像一个管子,里面可以装载一长条任何类型的东西.如需要对管子里的东西进行处理,则必须在管子内按直线顺序一个一个的来,这符合泛函编 ...
- 泛函编程(7)-数据结构-List-折叠算法
折叠算法是List的典型算法.通过折叠算法可以实现众多函数组合(function composition).所以折叠算法也是泛函编程里的基本组件(function combinator).了解折叠算法 ...
- 泛函编程(34)-泛函变量:处理状态转变-ST Monad
泛函编程的核心模式就是函数组合(compositionality).实现函数组合的必要条件之一就是参与组合的各方程序都必须是纯代码的(pure code).所谓纯代码就是程序中的所有表达式都必须是Re ...
- 泛函编程(30)-泛函IO:Free Monad-Monad生产线
在上节我们介绍了Trampoline.它主要是为了解决堆栈溢出(StackOverflow)错误而设计的.Trampoline类型是一种数据结构,它的设计思路是以heap换stack:对应传统递归算法 ...
- 泛函编程(29)-泛函实用结构:Trampoline-不再怕StackOverflow
泛函编程方式其中一个特点就是普遍地使用递归算法,而且有些地方还无法避免使用递归算法.比如说flatMap就是一种推进式的递归算法,没了它就无法使用for-comprehension,那么泛函编程也就无 ...
- 泛函编程(25)-泛函数据类型-Monad-Applicative
上两期我们讨论了Monad.我们说Monad是个最有概括性(抽象性)的泛函数据类型,它可以覆盖绝大多数数据类型.任何数据类型只要能实现flatMap+unit这组Monad最基本组件函数就可以变成Mo ...
- 怎样学习Scala泛函编程
确切来说应该是我打算怎么去学习Scala泛函编程.在网上找不到系统化完整的Scala泛函编程学习资料,只好把能找到的一些书籍.博客.演讲稿.论坛问答.技术说明等组织一下,希望能达到学习目的.关于Sca ...
- 泛函编程(14)-try to map them all
虽然明白泛函编程风格中最重要的就是对一个管子里的元素进行操作.这个管子就是这么一个东西:F[A],我们说F是一个针对元素A的高阶类型,其实F就是一个装载A类型元素的管子,A类型是相对低阶,或者说是基础 ...
随机推荐
- Maven3路程(三)用Maven创建第一个web项目(2)servlet演示
上一章用Maven新建了web项目成功后,本文演示在此基础上应用servlet. 1.首先修改pom.xml文件,添加servlet依赖 <project xmlns="http:// ...
- Tomcat and solr 环境配置
Tomcat and solr tomcat 安装 下载安装tomcat8.0 http://tomcat.apache.org/download-80.cgi wget http://apache. ...
- sys.stdout sys.stderr的用法
stdout:标准输出 stderr:标准错误 print 相当于 sys.stdout.write() + 换行 一个将数据流写入文件的程序,文件名为:main.py def main(out=s ...
- swift 枚举类型
1:swift的枚举类型是一系列的值,不同于c语言中枚举类型是整数类型.每个枚举定义了个新的类型 2:switch类型匹配 2.1枚举类型和switch单个匹配 enum PlatType{ case ...
- sap IRfcTable 转成 DataTable
public DataTable GetDataTableFromRFCTable(IRfcTable myrfcTable) { DataTable loTable = new DataTable( ...
- CSS3实现倒计时
CSS3实现倒计时小程序,界面如下: 代码如下: <style> body,html{ margin:0px; height:100%; } body{background: #000; ...
- [Linux] 查看系统启动时间
查找系统最后启动时间 1. 使用 who 命令 who -b 输出: system boot 2015-10-14 00:51 2. 使用 last 命令 last reboot | head -1 ...
- 自定义一个叫 ReadOnlyXmlMembershipProvider 的 MembershipProvider,用 XML 作为用户储藏室
1. 配置 web.config <membership defaultProvider="AspNetReadOnlyXmlMembershipProvider"> ...
- java 去掉html标签
使用正则表达式删除HTML标签. import java.util.regex.Matcher; import java.util.regex.Pattern; public class HTMLSp ...
- C#序列化JSON
public static string ConvertToJsonString<T>(T instance) { using (MemoryStream stre ...