Scalaz(19)- Monad: \/ - Monad 版本的 Either

简介:

  scala标准库提供了一个Either类型,它可以说是Option的升级版。与Option相同,Either也有两种状态:Left和Right,分别对应Option的None和Some,不同的是Left可以返回一个值。我们通常用这个值来表述异常信息。scalaz也提供了自己版本的Either,并用\/来分辨表示,以及两种状态-\/和\/-。我想scalaz特别提供\/是有原因的:\/不单是一种类型,它是一种type class。更重要的是\/是一种Monad,具备了函数组合能力(composibility)。如此能够方便把Either功能整合到FP编程中去。我们先看看\/的定义:scalaz/Either.scala


sealed abstract class \/[+A, +B] extends Product with Serializable {
...
  def isLeft: Boolean =
    this match {
      case -\/(_) => true
      case \/-(_) => false
    }

  /** Return `true` if this disjunction is right. */
  def isRight: Boolean =
    this match {
      case -\/(_) => false
      case \/-(_) => true
    }
...
 /** Return the right value of this disjunction or the given default if left. Alias for `|` */
  def getOrElse[BB >: B](x: => BB): BB =
    this match {
      case -\/(_) => x
      case \/-(b) => b
    }

  /** Return the right value of this disjunction or the given default if left. Alias for `getOrElse` */
  def |[BB >: B](x: => BB): BB =
    getOrElse(x)

  /** Return the right value of this disjunction or run the given function on the left. */
  def valueOr[BB >: B](x: A => BB): BB =
    this match {
      case -\/(a) => x(a)
      case \/-(b) => b
    }

  /** Return this if it is a right, otherwise, return the given value. Alias for `|||` */
  def orElse[AA >: A, BB >: B](x: => AA \/ BB): AA \/ BB =
    this match {
      case -\/(_) => x
      case \/-(_) => this
    }

  /** Return this if it is a right, otherwise, return the given value. Alias for `orElse` */
  def |||[AA >: A, BB >: B](x: => AA \/ BB): AA \/ BB =
    orElse(x)
...

与Option相同:\/也提供了函数来获取运算值(Right[A]),如getOrElse。那么如何获取异常信息呢?可以用swap后再用getOrElse:


/** Flip the left/right values in this disjunction. Alias for `unary_~` */
  def swap: (B \/ A) =
    this match {
      case -\/(a) => \/-(a)
      case \/-(b) => -\/(b)
    }

  /** Flip the left/right values in this disjunction. Alias for `swap` */
  def unary_~ : (B \/ A) =
    swap

"ah, error!".left[Int].getOrElse("no error")      //> res2: Any = no error
"ah, error!".left[Int].swap.getOrElse("no error") //> res3: String = ah, error!
(~"ah, error!".left[Int]).getOrElse("no error")   //> res4: String = ah, error!

与Option一样,\/也有两种状态:


/** A left disjunction
 *
 * Often used to represent the failure case of a result
 */
final case class -\/[+A](a: A) extends (A \/ Nothing)

/** A right disjunction
 *
 * Often used to represent the success case of a result
 */
final case class \/-[+B](b: B) extends (Nothing \/ B)

\/实现了map和flatMap:


/** Map on the right of this disjunction. */
  def map[D](g: B => D): (A \/ D) =
    this match {
      case \/-(a)     => \/-(g(a))
      case b @ -\/(_) => b
    }
 /** Bind through the right of this disjunction. */
  def flatMap[AA >: A, D](g: B => (AA \/ D)): (AA \/ D) =
    this match {
      case a @ -\/(_) => a
      case \/-(b) => g(b)
    }

注意flatMap:如果状态为\/- 则连续运算g(b),如果状态为-\/ 则立即停止运算返回-\/状态。这与Option功能相当。我们用for-comprehension来证明:


val epok = for {
    a <- \/-(3)
    b <- \/-(2)
} yield a + b                                     //> epok  : scalaz.\/[Nothing,Int] = \/-(5)
val epno = for {
    a <- \/-(3)
    c <- -\/("breaking out...")
    b <- \/-(2)
} yield a + b                                     //> epno  : scalaz.\/[String,Int] = -\/(breaking out...)
if (epno.isLeft) (~epno).getOrElse("no error")    //> res5: Any = breaking out...

\/在for-comprehension里的运算行为与Option一致。不过这个\/写法比较别扭。\/type class为任何类型提供了注入方法left和right: scalaz.syntax/EitherOps.scala


final def left[B]: (A \/ B) =
    -\/(self)

  final def right[B]: (B \/ A) =
    \/-(self)
}

trait ToEitherOps { //可以为任何类型A注入方法
  implicit def ToEitherOps[A](a: A) = new EitherOps(a)
}

现在这个for-comprehension可以这样写:


val epok1 = for {
    a <- 3.right
    b <- 2.right
} yield a + b                                     //> epok1  : scalaz.\/[Nothing,Int] = \/-(5)
val epno1 = for {
    a <- 3.right
    c <- "breaking out...".left[Int]
    b <- 2.right
} yield a + b                                     //> epno1  : scalaz.\/[String,Int] = -\/(breaking out...)
if (epno1.isLeft) (~epno1).getOrElse("no error")  //> res6: Any = breaking out...

这样表述是不是清晰直白多了。


相关文章
资源块|带你读《5G空口特性与关键技术》之九
3GPP TS38.211 中对 Point A 进行了定义。需要说明的是,2018/6 版本的TS38.211-f20 中的定义在 2018/9 版本中没有变化,不过在2018/12 版本 TS38.211-f40 中,基于 RAN1#94b 会议的决议进行了修改,有关信息请参看 RAN1#94b会议报告以及提案 R1-1811817 和 R11810834。
13261 2
资源块|带你读《5G空口特性与关键技术》之九
|
Ubuntu Linux C语言
还在用Alpine作为你Docker的Python开发基础镜像?其实Ubuntu更好一点
一般情况下,当你想为你的Python开发环境选择一个基础镜像时,大多数人都会选择Alpine,为什么?因为它太小了,仅仅只有 5 MB 左右(对比 Ubuntu 系列镜像接近 100 MB),但事实的真相是,我们选择基础镜像并不是为了体验一下Python语法而已,在此基础上,我们需要调试和安装各种扩展,可能会安装很多三方依赖,甚至预设更多服务,在这种环境下,Alpine就并非是一个很好的选择了,本次我们就来分别在Alpine和Ubuntu上来体验一下安装和编译Python的区别。
还在用Alpine作为你Docker的Python开发基础镜像?其实Ubuntu更好一点
|
SQL Oracle 关系型数据库
PLSQL查询Oracle表中文乱码解决
PLSQL查询Oracle表中文乱码解决
808 0
PLSQL查询Oracle表中文乱码解决
【异常】svn: E200009: Commit failed (details follow)/both sides of the move must be committed together的解决办法
svn: E200009: Commit failed (details follow)/both sides of the move must be committed together的解决办法
1409 0
【Shiro】7、Shiro实现控制用户并发登录并踢人下线(下)
在传统的项目中,同一账户是允许多人同时登录在线的,有的使用场景恰恰是不允许多人同时在线的,那么我们可以通过 Shiro 来控制并发登录,并实现后登录的用户,挤掉前面登录的用户
897 0
|
SQL 消息中间件 缓存
阿里云大数据开发三面面经,已过,面试题已配答案
阿里云大数据开发三面面经,已过,面试题已配答案
1900 1
|
SQL 数据采集 存储
数据建设与治理丨Dataphin中如何进行Hologres开发
前言:在Dataphin 3.9中新增支持Hologres引擎的适配。Hologres是一站式实时数据仓库引擎,支持海量数据实时写入、实时更新、实时分析,支持标准SQL(兼容PostgreSQL协议),支持PB级数据多维分析(OLAP)与即席分析(Ad Hoc),支持高并发低延迟的在线数据服务(Serving)。通过Dataphin的研发平台能力以及数据资产治理能力,可提供更好的即席分析及实时数仓的构建能力。
1023 0
数据建设与治理丨Dataphin中如何进行Hologres开发
|
监控 网络协议 Linux
同步时间,为什么我选 chrony 而不是 NTP ?
同步时间,为什么我选 chrony 而不是 NTP ?
|
网络协议 虚拟化 网络虚拟化
VXLAN小实验:集中式VXLAN IP网关配置
VXLAN小实验:集中式VXLAN IP网关配置
VXLAN小实验:集中式VXLAN IP网关配置
|
前端开发 NoSQL Java
19、SpringBoot2.0中响应式编程和 WebFlux 入门(十九)
Spring 5.0 中发布了重量级组件 Webflux,拉起了响应式编程的规模使用序幕。
723 0
19、SpringBoot2.0中响应式编程和 WebFlux 入门(十九)

热门文章

最新文章