Scalaz(2)- 基础篇:随意多态-typeclass, ad-hoc polymorphism

简介:

  scalaz功能基本上由以下三部分组成:

1、新的数据类型,如:Validation, NonEmptyList ...

2、标准scala类型的延伸类型,如:OptionOps, ListOps ...

3、通过typeclass的随意多态(ad-hoc polymorphism)编程模式实现的大量概括性函数组件库

我们在这篇重点讨论多态(polymorphism),特别是随意多态(ad-hoc polymorphism)。

多态,简单来讲就是一项操作(operation)可以对任意类型施用。在OOP的世界里,我们可以通过以下各种方式来实现多态:

1、重载 Overloading

2、继承 Inheritance

3、模式匹配 Pattern-matching

4、特性 Traits/interfaces

5、类型参数 Type parameters

作为一种通用的组件库,scalaz是通过任意多态typeclass模式来实现软件模块之间的松散耦合(decoupling).这样scalaz的用户就可以在不需要重新编译scalaz源代码的情况下对任何类型施用scalaz提供的函数功能了。

我们来分析一下各种实现多态的方式:

假如我们设计一个描述输入参数的函数:tell(t: some type): String

如:tell(c: Color) >>> "I am color Red"

    tell(i: Int) >>> "I am Int 3"

    tell(p: Person) >>> "I am Peter"

如果用Overloading:


object overload {
 case class Color(descript: String)
 case class Person(name: String)

 def tell(c: Color) = "I am color "+ c.descript
 def tell(p: Person) = "I am "+ p.name
}

我们看到用重载的话,除了相同的函数名称tell之外这两个函数没有任何其它关系。我们必须对每一个不同的类型提供一个独立的tell函数。这种方式没什么用,我们需要的是一个函数施用在不同的类型上。

再试试用继承Inheritance:


trait Thing {
  def tell: String
}
class  Color(descript: String) extends Thing {
  override def tell: String = "I am color " + descript
}
class Person(name: String) extends Thing {
  override def tell: String = "I am " + name
}

new Color("RED").tell                             //> res0: String = I am color RED
new Person("John").tell                           //> res1: String = I am John

这种方式更糟糕,tell和类有着更强的耦合。用户必须拥有这些类的源代码才能实现tell。试想如果这个类型是标准的Int怎么办。

用模式匹配pattern-matching呢?


case class Color(descript: String)
case class Person(name: String)
def tell(x: Any): String = x match {
  case Color(descr) => "I am color " + descr
  case Person(name) => "I am " + name
  case i: Int => "I am Int "+i
  case _ => "unknown"
}                                                 //> tell: (x: Any)String

tell(23)                                          //> res0: String = I am Int 23
tell(Color("RED"))                                //> res1: String = I am color RED
tell(Person("Peter"))                             //> res2: String = I am Peter

Pattern-matching倒是可以把tell和类型分开。但是必须在tell里增加新的类型匹配,也就是说必须能控制tell的源代码。

现在再尝试用typeclass模式:typeclass模式是由trait加implicit组成。先看看trait: 


1 trait Tellable[T] {
2   def tell(t: T): String
3 }

这个trait Tellable代表的意思是把tell功能附加到任意类型T,但还未定义tell的具体功能。

如果用户想把tell附加给Color类型:


trait Tellable[T] {
  def tell(t: T): String
}
case class Color(descript: String)
case class Person(name: String)
object colorTeller extends Tellable[Color] {
    def tell(t: Color): String = "I am color "+t.descript
}

针对Color我们在object colorTeller里实现了tell。现在更概括的tell变成这样: 


1 def tell[T](t: T)(M: Tellable[T]) = {
2     M.tell(t)
3 }                                                 //> tell: [T](t: T)(M: scalaz.learn.demo.Tellable[T])String
4 tell(Color("RED"))(colorTeller)                   //> res0: String = I am color RED

这个版本的tell增加了类型变量T、输入参数M,意思是对任何类型T,因为M可以对任何类型T施用tell,所以这个版本的tell可以在任何类型上施用。上面的例子调用了针对Color类型的tell。那么针对Person的tell我们再实现一个Tellable[Person]实例就行了吧:


val personTeller = new Tellable[Person] {
    def tell(t: Person): String = "I am "+ t.name
}                                                 //> personTeller  : scalaz.learn.demo.Tellable[scalaz.learn.demo.Person] = scala
                                                  //| z.learn.demo$$anonfun$main$1$$anon$1@13969fbe
tell(Person("John"))(personTeller)                //> res1: String = I am John
val intTeller = new Tellable[Int] {
    def tell(t: Int): String = "I am Int "+ t.toString
}                                                 //> intTeller  : scalaz.learn.demo.Tellable[Int] = scalaz.learn.demo$$anonfun$ma
                                                  //| in$1$$anon$2@6aaa5eb0
tell(43)(intTeller)                               //> res2: String = I am Int 43

如上,即使针对Int类型我们一样可以调用这个tell[T]。也既是说如果这个概括性的tell[T]是由其他人开发的某些组件库提供的,那么用户只要针对他所需要处理的类型提供一个tell实现实例,然后调用这个共享的tell[T],就可以得到随意多态效果了。至于这个类型的实现细节或者源代码则不在考虑之列。

好了,现在我们可以用implicit来精简tell[T]的表达形式:


1 def tell[T](t: T)(implicit M: Tellable[T]) = {
2     M.tell(t)
3 }                                                 //> tell: [T](t: T)(implicit M: scalaz.learn.demo.Tellable[T])String

 也可以这样写:


1 def tell[T : Tellable](t: T) = {
2     implicitly[Tellable[T]].tell(t)
3 }                                                 //> tell: [T](t: T)(implicit evidence$1: scalaz.learn.demo.Tellable[T])String

  现在看看如何调用tell:


implicit object colorTeller extends Tellable[Color] {
    def tell(t: Color): String = "I am color "+t.descript
}

tell(Color("RED"))                                //> res0: String = I am color RED

implicit val personTeller = new Tellable[Person] {
    def tell(t: Person): String = "I am "+ t.name
}                                                 //> personTeller  : scalaz.learn.demo.Tellable[scalaz.learn.demo.Person] = scala
                                                  //| z.learn.demo$$anonfun$main$1$$anon$1@3498ed
tell(Person("John"))                              //> res1: String = I am John

implicit val intTeller = new Tellable[Int] {
    def tell(t: Int): String = "I am Int "+ t.toString
}                                                 //> intTeller  : scalaz.learn.demo.Tellable[Int] = scalaz.learn.demo$$anonfun$ma
                                                  //| in$1$$anon$2@1a407d53
tell(43)                                          //> res2: String = I am Int 43

假如我忽然需要针对新的类型List[Color], 我肯定无须理会tell[T],只要调用它就行了:


implicit object listTeller extends Tellable[List[Color]] {
    def tell(t: List[Color]): String = {
        (t.map(c => c.descript)).mkString("I am list of color [",",","]")
    }
}

tell[List[Color]](List(Color("RED"),Color("BLACK"),Color("YELLOW"),Color("BLUE")))
                                                  //> res3: String = I am list of color [RED,BLACK,YELLOW,BLUE]

这才是真正的随意多态。

值得注意的是implicit是scala compiler的一项功能。在编译时compiler发现类型不对称就会进行隐式转换解析(implicit resolution)。如果解析失败则程序无法通过编译。如果我这样写: tell(4.5),compiler会提示语法错误。而上面其它多态方式则必须在运算时(runtime)才能发现错误。


相关实践学习
使用CLup和iSCSI共享盘快速体验PolarDB for PostgtreSQL
在Clup云管控平台中快速体验创建与管理在iSCSI共享盘上的PolarDB for PostgtreSQL。
AnalyticDB PostgreSQL 企业智能数据中台:一站式管理数据服务资产
企业在数据仓库之上可构建丰富的数据服务用以支持数据应用及业务场景;ADB PG推出全新企业智能数据平台,用以帮助用户一站式的管理企业数据服务资产,包括创建, 管理,探索, 监控等; 助力企业在现有平台之上快速构建起数据服务资产体系
相关文章
|
15天前
|
安全
Vuex惊天漏洞!!!破解Vuex状态管理漏洞:让getters变量具有set赋值的能力,支持双向绑定
Vuex惊天漏洞!!!破解Vuex状态管理漏洞:让getters变量具有set赋值的能力,支持双向绑定
|
10月前
|
测试技术
Rational Rose UseCaseView LogicalView ComponentView DeploymentView 四种视图含义
Rational Rose UseCaseView LogicalView ComponentView DeploymentView 四种视图含义
67 0
|
11月前
|
Shell 数据安全/隐私保护 Python
ansible学习之旅(ad-hoc与常见模块)
ansible学习之旅(ad-hoc与常见模块)
155 0
|
11月前
|
JSON Java 数据库
代码重构实战-将值对象改为引用对象(Change Value to Reference)
一个数据结构中可能包含多个记录,而这些记录都关联到同一个逻辑数据结构。例如,我可能会读取一系列订单数据,其中有多条订单属于同一个顾客。遇到这样的共享关系,既能将顾客信息作为值对象看待,也能将其视为引用对象
81 0
Rational Rose中的Package命名方法(用小矩形命名)
Rational Rose中的Package命名方法(用小矩形命名)
74 0
Rational Rose中的Package命名方法(用小矩形命名)
|
JavaScript 前端开发 安全
TypeScript 4.9 beta 发布:鸽置的 ES 装饰器、satisfies 操作符、类型收窄增强、单文件级别配置等
TypeScript 已于 2022.09.23 发布 4.9 beta 版本,你可以在 [4.9 Iteration Plan](https://github.com/microsoft/TypeScript/issues/50457) 查看所有被包含的 Issue 与 PR。如果想要抢先体验新特性,执行: ```bash $ npm install typescript@beta ```
|
存储 编解码
ES6新特性(8)之Decorator修饰器/二进制数组
ES6新特性(8)之Decorator修饰器/二进制数组