Scalaz(4)- typeclass:标准类型-Equal,Order,Show,Enum

  Scalaz是由一堆的typeclass组成。每一个typeclass具备自己特殊的功能。用户可以通过随意多态(ad-hoc polymorphism)把这些功能施用在自己定义的类型上。scala这个编程语言借鉴了纯函数编程语言Haskell的许多概念。typeclass这个名字就是从Haskell里引用过来的。只不过在Haskell里用的名称是type class两个分开的字。因为scala是个OOP和FP多范畴语言,为了避免与OOP里的type和class发生混扰,所以就用了typeclass一个字。实际上scalaz就是Haskell基本库里大量typeclass的scala实现。

  在这篇讨论里我们可以通过介绍scalaz的一些比较简单的typeclass来了解scalaz typeclass的实现、应用方法以及scalaz函数库的内部结构。

  我们首先看看Equal:这是个比较典型的typeclass,适合用来介绍scalaz typeclass的一些实现方式、应用模式以及函数库结构。

我们知道,scalaz typeclass的几个重要元素就是:

1、特质 trait

2、隐式实例 implicit instances

3、方法注入 method injection

Equal Trait 在 core/.../scalaz/Equal.scala里,比较简单:

trait Equal[F]  { self =>
  ////
  def equal(a1: F, a2: F): Boolean

  def contramap[G](f: G => F): Equal[G] = new Equal[G] {
    def equal(a1: G, a2: G) = self.equal(f(a1), f(a2))
  }

  /** @return true, if `equal(f1, f2)` is known to be equivalent to `f1 == f2` */
  def equalIsNatural: Boolean = false
...

只要实现equal(a1,a2)这个抽象函数就可以了。Equal typeclass主要的功能就是对两个相同类型的元素进行等比。那和标准的 == 符号什么区别呢?Equal typeclass提供的是类型安全(type safe)的等比,在编译时由compiler发现错误,如下面的例子:

cala> 2 == 2.0
res3: Boolean = true

scala> 2 === 2.0
<console>:14: error: type mismatch;
 found   : Double(2.0)
 required: Int
              2 === 2.0
                    ^

以上的 === 是Equal typeclass的符号方法(symbolic method),就是这个equal(a1,a2),是通过方法注入加入到Equal typeclass里的。我们可以看到equal对两个比对对象的类型要求是非常严格的,否则无法通过编译(除非在隐式作用域implicit scode内定义Double到Int的隐式转换implicit conversion)。

但是,在Equal Trait里的equal是个抽象函数(abstract function),没有实现。那么肯定在隐式作用域(implicit scope)里存在着隐式Equal实例。比如以上的例子我们应该试着找找Equal的Int实例。

我在scalaz.std/AnyValue.scala里发现了这段代码:

implicit val intInstance: Monoid[Int] with Enum[Int] with Show[Int] = new Monoid[Int] with Enum[Int] with Show[Int] {
    override def shows(f: Int) = f.toString

    def append(f1: Int, f2: => Int) = f1 + f2

    def zero: Int = 0

    def order(x: Int, y: Int) = if (x < y) Ordering.LT else if (x == y) Ordering.EQ else Ordering.GT

    def succ(b: Int) = b + 1
    def pred(b: Int) = b - 1
    override def succn(a: Int, b: Int) = b + a
    override def predn(a: Int, b: Int) = b - a
    override def min = Some(Int.MinValue)
    override def max = Some(Int.MaxValue)

    override def equalIsNatural: Boolean = true
  }

这是个Int实例。但好像没有继承Equal trait,因而也没有发现equal函数的实现。但是它继承了Enum。那么在scalaz/Enum.scala中的Enum trait是这样的:

1 trait Enum[F] extends Order[F] { self =>

Enum又继承了Order,再到scalaz/order.scala看看Order trait:

trait Order[F] extends Equal[F] { self =>
  ////
  def apply(x: F, y: F): Ordering = order(x, y)

  def order(x: F, y: F): Ordering 

  def equal(x: F, y: F): Boolean = order(x, y) == Ordering.EQ

原来Order就是Equal,所以Enum就是Equal。equal(a1,a2)是在Order trait里用order(a1,a2)实现的,而order(a1,a2)是在Int隐式实例intInstance里实现了。这样就解决了隐式实例的问题,所以我们可以使用 2.===(2.0) >>> 2 === 2.0这样的语法。

我们再来看看方法注入是怎么实现的吧。Scalaz方法注入标准写法:放在scalaz/syntax/EqualSyntax.scala里:

/** Wraps a value `self` and provides methods related to `Equal` */
final class EqualOps[F] private[syntax](val self: F)(implicit val F: Equal[F]) extends Ops[F] {
  ////

  final def ===(other: F): Boolean = F.equal(self, other)
  final def /==(other: F): Boolean = !F.equal(self, other)
  final def =/=(other: F): Boolean = /==(other)
  final def ≟(other: F): Boolean = F.equal(self, other)
  final def ≠(other: F): Boolean = !F.equal(self, other)

  /** Raises an exception unless self === other. */
  final def assert_===[B](other: B)(implicit S: Show[F], ev: B <:< F) =
      if (/==(other)) sys.error(S.shows(self) + " ≠ " + S.shows(ev(other)))

  ////
}

scalaz一般把字符方法(symbolic method)放在scalaz/syntax目录下。也就是 ===, =/=这两个操作符号,对应的是 ==, !=这两个标准操作符。注意这个符号方法容器类EqualOps需要一个隐式参数(implicit parameter)F: Equal[F],因为具体的equal(a1,a2)是在Equal[F]的实例里实现的。具体的方法注入黏贴还是通过隐式解析实现的:

trait ToEqualOps  {
  implicit def ToEqualOps[F](v: F)(implicit F0: Equal[F]) =
    new EqualOps[F](v)

  ////

  ////
}

但是这个隐式转换ToEqualOps为什么是在trait里?隐式作用域必须是在某个object里的。我们再看看scalaz/syntax/syntax.scala里的这一段代码;

trait ToTypeClassOps
  extends ToSemigroupOps with ToMonoidOps with ToEqualOps with ToShowOps
  with ToOrderOps with ToEnumOps with ToPlusEmptyOps
  with ToFunctorOps with ToContravariantOps with ToApplyOps
  with ToApplicativeOps with ToBindOps with ToMonadOps with ToComonadOps
  with ToBifoldableOps with ToCozipOps
  with ToPlusOps with ToApplicativePlusOps with ToMonadPlusOps with ToTraverseOps with ToBifunctorOps
  with ToBitraverseOps with ToComposeOps with ToCategoryOps
  with ToArrowOps with ToFoldableOps with ToChoiceOps with ToSplitOps with ToZipOps with ToUnzipOps with ToMonadTellOps with ToMonadListenOps with ToMonadErrorOps
  with ToFoldable1Ops with ToTraverse1Ops with ToOptionalOps with ToCatchableOps with ToAlignOps

trait ToTypeClassOps继承了ToEqualOps。然后在scalaz/Scalaz.scala里:

object Scalaz
  extends StateFunctions        // Functions related to the state monad
  with syntax.ToTypeClassOps    // syntax associated with type classes
  with syntax.ToDataOps         // syntax associated with Scalaz data structures
  with std.AllInstances         // Type class instances for the standard library types
  with std.AllFunctions         // Functions related to standard library types
  with syntax.std.ToAllStdOps   // syntax associated with standard library types
  with IdInstances              // Identity type and instances

object Scalaz继承了ToTypeClassOps。这样ToEqualOps的隐式作用域就在object Scalaz里了。

为了方便使用,Equal typeclass提供了构建函数:

1   def equal[A](f: (A, A) => Boolean): Equal[A] = new Equal[A] {
2     def equal(a1: A, a2: A) = f(a1, a2)
3   }

我们可以这样构建Equal实例:

scala> case class Person(name: String, age: Int)
defined class Person
scala> implicit val personEqual: Equal[Person] = Equal.equal{(a,b) => a.name == b.name && a.age == b.age}
personEqual: scalaz.Equal[Person] = scalaz.Equal$$anon$7@7e5716e

scala> Person("Jone",23) === Person("Jone",23)
res0: Boolean = true

scala> Person("Jone",23) === Person("Jone",22)
res1: Boolean = false

scala> Person("Jone",23) === Person("John",23)
res2: Boolean = false

当然我们也可以通过实现抽象函数equal(a1,a2)函数的方式来构建Equal实例:

scala> implicit val personEqual = new Equal[Person] {
     | def equal(a1: Person, a2: Person): Boolean = a1.name == a2.name && a1.age == a2.age
     | }
personEqual: scalaz.Equal[Person] = $anon$1@247cc8f

scala> Person("John",32) === Person("Joe",32)
res0: Boolean = false

scala> Person("John",32) === Person("John",32)
res1: Boolean = true

在Equal trait 里有个有趣的函数:

1  def contramap[G](f: G => F): Equal[G] = new Equal[G] {
2     def equal(a1: G, a2: G) = self.equal(f(a1), f(a2))
3   }

从函数名称来看它是个逆变(contra)。把函数款式概括化如下:

def contramap[G](f: G => F): Equal[F] => Equal[G]

它的意思是说:如果提供G => F转换关系,就可以把Equal[F]转成Equal[G]。与正常的转换函数map比较:

def map[G](f: F => G): Equal[F] => Equal[G]

函数f是反方向的,因而称之逆变contramap。Equal的伴生对象提供了另外一个构建函数:

1   def equalBy[A, B: Equal](f: A => B): Equal[A] = Equal[B] contramap f

equalBy的意思是:假如已经有了Equal[B]实例,如果能提供A => B得转换,就可以通过equalBy构建Equal[A]实例。

举例:case class MoneyCents(cents: Int)

我们有现成的Equal[Int]实例,只要能提供MoneyCents与Int之间的转换关系,我们就可以等比MoneyCents了:

scala> case class MoneyCents(cents: Int)
defined class MoneyCents
scala> def moneyToInt(m: MoneyCents): Int = m.cents * 100
moneyToInt: (m: MoneyCents)Int

scala> implicit val moneyEqual: Equal[MoneyCents] = Equal.equalBy(moneyToInt)
moneyEqual: scalaz.Equal[MoneyCents] = scalaz.Order$$anon$7@138ad7f5

scala> MoneyCents(120) === MoneyCents(120)
res2: Boolean = true

scala> MoneyCents(122) === MoneyCents(120)
res3: Boolean = false

这个逆变在以上例子的主要用途是:我们知道如何等比Int,我们又可以提供MoneyCents和Int之间的转换关系,那么我们就可以构建Equal[MoneyCents]实例。

介绍了Equal typeclass的实现和应用原理后,解释其它的typeclass就简单许多了。

我们再看看Order typeclass:

Scalaz的Order tyeclass提供了一组操作符号:在scalaz/syntax/OrderSyntax.scala里

/** Wraps a value `self` and provides methods related to `Order` */
final class OrderOps[F] private[syntax](val self: F)(implicit val F: Order[F]) extends Ops[F] {
  ////
  final def <(other: F): Boolean = F.lessThan(self, other)
  final def <=(other: F): Boolean = F.lessThanOrEqual(self, other)
  final def >(other: F): Boolean = F.greaterThan(self, other)
  final def >=(other: F): Boolean = F.greaterThanOrEqual(self, other)
  final def max(other: F): F = F.max(self, other)
  final def min(other: F): F = F.min(self, other)
  final def cmp(other: F): Ordering = F.order(self, other)
  final def ?|?(other: F): Ordering = F.order(self, other)
  final def lte(other: F): Boolean = F.lessThanOrEqual(self, other)
  final def gte(other: F): Boolean = F.greaterThanOrEqual(self, other)
  final def lt(other: F): Boolean = F.lessThan(self, other)
  final def gt(other: F): Boolean = F.greaterThan(self, other)
  ////
}

其中cmp(?|?)方法使用了Ordering类型。Ordering是另外一个typeclass: scalaz/Ordering.scala

1 object Ordering extends OrderingInstances with OrderingFunctions {
2   case object LT extends Ordering(-1, "LT") { def complement = GT }
3   case object EQ extends Ordering(0,  "EQ") { def complement = EQ }
4   case object GT extends Ordering(1,  "GT") { def complement = LT }
5 }

主要定义了LT,EQ,GT三个状态。

我们应该尽量使用lt,lte,gt,gte来确保类型安全(让compiler来发现错误):

scala> 1 < 1.0
res4: Boolean = false

scala> 1 lt 1.0
<console>:21: error: type mismatch;
 found   : Double(1.0)
 required: Int
              1 lt 1.0
                   ^

scala> 1 ?|? 1.0
<console>:21: error: type mismatch;
 found   : Double(1.0)
 required: Int
              1 ?|? 1.0
                    ^

scala> 1 ?|? 2
res7: scalaz.Ordering = LT

scala> 1 lt 2
res8: Boolean = true

与Equal typeclass 同样,如果我们需要在自定义的类型T上使用Order typeclass的话,有几种方法可以构建Order[T]:

1、实现Order trait抽象函数order(a1,a2),在scalaz/std/AnyValue.scala中的Int实例intInstance中是这样实现order(a1,a2)函数的:

1     def order(x: Int, y: Int) = if (x < y) Ordering.LT else if (x == y) Ordering.EQ else Ordering.GT

我们可以在Person类型上使用Order:

scala> case class Person(name: String, age: Int)
defined class Person

scala> implicit val personAgeOrder = new Order[Person] {
     | def order(a1: Person, a2: Person): Ordering =
     | if (a1.age < a2.age) Ordering.LT else if (a1.age > a2.age) Ordering.GT else Ordering.EQ
     | }
personAgeOrder: scalaz.Order[Person] = $anon$1@736d65e9
scala> Person("John",23) ?|? Person("Joe",24)
res11: scalaz.Ordering = LT

scala> Person("John",23) lt  Person("Joe",24)
res12: Boolean = true

scala> Person("John",23) gt  Person("Joe",24)
res13: Boolean = false

2、用object Order里的构建函数order[A](f: (A,A) => Ordering): Order[A]

scala> case class Meat(cat: String, weight: Int)
defined class Meat
scala> implicit val meatWeightOrder: Order[Meat] = Order.order(_.weight ?|? _.weight)
meatWeightOrder: scalaz.Order[Meat] = scalaz.Order$$anon$11@7401c09f

scala> Meat("Pork",13) lt Meat("Pork",14)
res14: Boolean = true

scala> Meat("Beef",13) gt Meat("Pork",14)
res15: Boolean = false

3、逆变构建函数orderBy:

scala> case class Money(amount: Int)
defined class Money

scala> val  moneyToInt: Money => Int = money => money.amount
moneyToInt: Money => Int = <function1>

scala> implicit val moneyOrder: Order[Money] = Order.orderBy(moneyToInt)
moneyOrder: scalaz.Order[Money] = scalaz.Order$$anon$7@3e3975d0

scala> Money(20) lt Money(21)
res16: Boolean = true

scala> Money(20) ?|? Money(12)
res17: scalaz.Ordering = GT

在使用逆变构建函数时我们不需要再考虑如何实现对两个对象值的对比来获取这个Ordering返回值,我们只知道Order[Int]实现了两个Int的对比就行了。

Show 是一个简单的typeclass。我们用Shows(T)来实现对类型T的字符描述:

在scalaz/Syntax/ShowSyntax.scala里的注入方法:

final class ShowOps[F] private[syntax](val self: F)(implicit val F: Show[F]) extends Ops[F] {
  ////
  final def show: Cord = F.show(self)
  final def shows: String = F.shows(self)
  final def print: Unit = Console.print(shows)
  final def println: Unit = Console.println(shows)
  ////
}

我们用Show来描述Person类型:

scala> case class Person(name: String, age: Int)
defined class Person
scala> implicit val personShow: Show[Person] = Show.show {p => p.name + "," + p.age + " years old" }
personShow: scalaz.Show[Person] = scalaz.Show$$anon$4@1d80fcd3
res19: String = Harry,24 years old

scala> Person("Harry",24).shows
res20: String = Harry,24 years old

scala> Person("Harry",24).println
Harry,24 years old

Enum typeclass 提供了下面这些方法:

final class EnumOps[F] private[syntax](val self: F)(implicit val F: Enum[F]) extends Ops[F] {
  ////
  final def succ: F =
    F succ self

  final def -+-(n: Int): F =
    F.succn(n, self)

  final def succx: Option[F] =
    F.succx.apply(self)

  final def pred: F =
    F pred self

  final def ---(n: Int): F =
    F.predn(n, self)

  final def predx: Option[F] =
    F.predx.apply(self)

  final def from: EphemeralStream[F] =
    F.from(self)

  final def fromStep(step: Int): EphemeralStream[F] =
    F.fromStep(step, self)

  final def |=>(to: F): EphemeralStream[F] =
    F.fromTo(self, to)

  final def |->(to: F): List[F] =
    F.fromToL(self, to)

  final def |==>(step: Int, to: F): EphemeralStream[F] =
    F.fromStepTo(step, self, to)

  final def |-->(step: Int, to: F): List[F] =
    F.fromStepToL(step, self, to)

  ////
}

下面是使用这些操作符号的例子:

scala> 'a' to 'e'
res22: scala.collection.immutable.NumericRange.Inclusive[Char] = NumericRange(a, b, c, d, e)

scala> 'a' |-> 'e'
res23: List[Char] = List(a, b, c, d, e)

scala> 'a' |=> 'e'
res24: scalaz.EphemeralStream[Char] = scalaz.EphemeralStreamFunctions$$anon$4@2f8a4dfd

scala> 'a'.succ
res25: Char = b
scala> 'a' -+- 2
res26: Char = c

scala> 'd' --- 2
res27: Char = b

Enum实例需要实现抽象函数succ,pred。下面是char裂隙Enum实例Enum[Char]的实现:在scalaz/std/AnyVal.scala里的char object

1     def succ(b: Char) = (b + 1).toChar
2     def pred(b: Char) = (b - 1).toChar
3     override def succn(a: Int, b: Char) = (b + a).toChar
4     override def predn(a: Int, b: Char) = (b - a).toChar

再仔细看看Enum trait如下;

trait Enum[F] extends Order[F] { self =>
  ////

  def succ(a: F): F
  def pred(a: F): F

Enum实例必须实现抽象函数succ,pred。除此之外由于Enum继承了Order,所以还必须实现Order trait的抽象函数order(a1,a2)。

时间: 2024-10-08 20:23:46

Scalaz(4)- typeclass:标准类型-Equal,Order,Show,Enum的相关文章

C标准类型的长度bytes

WIN2K/VC下面: [char] Size Total:1 [int] Size Total:4 [long int] Size Total:4 [float] Size Total:4 [double] Size Total:8 [long double] Size Total:8 [double point]Size Total:4 [char point] Size Total:4 WIN2K/dev-c++下面 & Ubuntu8.10 gcc 下面: [char] Size Tot

ruby 标准类型总结_ruby专题

一.数字 Ruby支持整数和浮点数,整数可以是任意长度 一定范围内的整数以二进制存放,它们属于fixnum类型,当超出这个范围时则自动转换为bignum类型 表达方式:符号+一串字符,数字串中的下划线会被忽略,(前缀包括:0表示八进制, 0x表示十六进制, 0b表示二进制)123_456_789_123_345_789 # Bignum0xaabb # 十六进制 也可以通过在前面加上问号来得到ASCII码字符对应的整数值和转义序列的值?a # 普通字符?\n # 换行符 (0x0a)?\C-a

介绍Java语言中枚举类型及如何定制Enum类型的定义

Enum 类型的介绍 枚举类型(Enumerated Type) 很早就出现在编程语言中,它被用来将一组类似的值包含到一种类型当中.而这种枚举类型的名称则会被定义成http://www.aliyun.com/zixun/aggregation/30537.html">独一无二的类型描述符,在这一点上和常量的定义相似.不过相比较常量类型,枚举类型可以为申明的变量提供更大的取值范围. 举个例子来说明一下,如果希望为彩虹描绘出七种颜色,你可以在 Java 程序中通过常量定义方式来实现. 清单 1

【C/C++学院】0814-引用高级、引用高级增加/auto自动变量自动根据类型创建数据/Bool/Enum/newdelete全局/大数据乘法与结构体/函数模板与auto/宽字符本地化/inline

引用高级.引用高级增加 #include<iostream> #include<stdlib.h> // int a[10] // int (&ra)[10] // int a[2][5] // int (&ra)[2][5] void main1() { int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int(&ra)[10](a);//引用就是给原来的变量有一个别名同一个地址 int i = 0; for (

Scalaz(8)- typeclass:Monoid and Foldable

 Monoid是种最简单的typeclass类型.我们先看看scalaz的Monoid typeclass定义:scalaz/Monoid.scala 1 trait Monoid[F] extends Semigroup[F] { self => 2 //// 3 /** The identity element for `append`. */ 4 def zero: F 5 ... Monoid trait又继承了Semigroup:scalaz/Semigroup.scala 1 tra

Scalaz(6)- typeclass:Functor-just map

  Functor是范畴学(Category theory)里的概念.不过无须担心,我们在scala FP编程里并不需要先掌握范畴学知识的.在scalaz里,Functor就是一个普通的typeclass,具备map over特性.我的理解中,Functor的主要用途是在FP过程中更新包嵌在容器(高阶类)F[T]中元素T值.典型例子如:List[String], Option[Int]等.我们曾经介绍过FP与OOP的其中一项典型区别在于FP会尽量避免中间变量(temp variables).FP

Scalaz(27)- Inference &amp; Unapply :类型的推导和匹配

  经过一段时间的摸索,用scala进行函数式编程的过程对我来说就好像是想着法儿如何将函数的款式对齐以及如何正确地匹配类型,真正是一种全新的体验,但好像有点太偏重学术型了. 本来不想花什么功夫在scala的类型系统上,但在阅读scalaz源代码时往往遇到类型层面的编程(type level programming),常常扰乱了理解scalaz代码思路,所以还是要简单的介绍一下scala类型系统的一些情况.scala类型系统在scala语言教材中一般都提及到了.但有些特殊的类型如phantom t

Scalaz(21)-类型例证:Liskov and Leibniz - type evidence

  Leskov,Leibniz,别扭的名字,是什么地干活?碰巧从scalaz源代码里发现了这么个东西:scalaz/BindSyntax.scala /** Wraps a value `self` and provides methods related to `Bind` */ final class BindOps[F[_],A] private[syntax](val self: F[A])(implicit val F: Bind[F]) extends Ops[F[A]] { //

Scalaz(11)- Monad:你存在的意义

 前面提到了scalaz是个函数式编程(FP)工具库.它提供了许多新的数据类型.拓展的标准类型及完整的一套typeclass来支持scala语言的函数式编程模式.我们知道:对于任何类型,我们只需要实现这个类型的typeclass实例就可以在对这个类型施用所对应typeclass提供的所有组件函数了(combinator).突然之间我们的焦点好像都放在了如何获取typeclass实例上了,从而忽略了考虑为什么要使用这些typeclass及使用什么样的typeclass这些问题了.所以可能有人会问我