博客
关于我
Scalaz(19)- Monad: \/ - Monad 版本的 Either
阅读量:459 次
发布时间:2019-03-06

本文共 4103 字,大约阅读时间需要 13 分钟。

  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来证明:

1 val epok = for { 2     a <- \/-(3) 3     b <- \/-(2) 4 } yield a + b                                     //> epok  : scalaz.\/[Nothing,Int] = \/-(5) 5 val epno = for { 6     a <- \/-(3) 7     c <- -\/("breaking out...") 8     b <- \/-(2) 9 } yield a + b                                     //> epno  : scalaz.\/[String,Int] = -\/(breaking out...)10 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可以这样写:

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

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

 

 

 

 

 

转载地址:http://gyefz.baihongyu.com/

你可能感兴趣的文章
NIFI从MySql中离线读取数据再导入到MySql中_无分页功能_02_转换数据_分割数据_提取JSON数据_替换拼接SQL_添加分页---大数据之Nifi工作笔记0037
查看>>
NIFI从Oracle11G同步数据到Mysql_亲测可用_解决数据重复_数据跟源表不一致的问题---大数据之Nifi工作笔记0065
查看>>
NIFI从PostGresql中离线读取数据再导入到MySql中_带有数据分页获取功能_不带分页不能用_NIFI资料太少了---大数据之Nifi工作笔记0039
查看>>
nifi使用过程-常见问题-以及入门总结---大数据之Nifi工作笔记0012
查看>>
NIFI分页获取Mysql数据_导入到Hbase中_并可通过phoenix客户端查询_含金量很高的一篇_搞了好久_实际操作05---大数据之Nifi工作笔记0045
查看>>
NIFI分页获取Postgresql数据到Hbase中_实际操作---大数据之Nifi工作笔记0049
查看>>
NIFI同步MySql数据_到SqlServer_错误_驱动程序无法通过使用安全套接字层(SSL)加密与SQL Server_Navicat连接SqlServer---大数据之Nifi工作笔记0047
查看>>
NIFI同步MySql数据源数据_到原始库hbase_同时对数据进行实时分析处理_同步到清洗库_实际操作06---大数据之Nifi工作笔记0046
查看>>
Nifi同步过程中报错create_time字段找不到_实际目标表和源表中没有这个字段---大数据之Nifi工作笔记0066
查看>>
【Flink】Flink 1.9 版本 web UI 突然没有日志
查看>>
NIFI大数据进阶_FlowFile拓扑_对FlowFile内容和属性的修改删除添加_介绍和描述_以及实际操作---大数据之Nifi工作笔记0023
查看>>
NIFI大数据进阶_FlowFile生成器_GenerateFlowFile处理器_ReplaceText处理器_处理器介绍_处理过程说明---大数据之Nifi工作笔记0019
查看>>
NIFI大数据进阶_FlowFile生成器_GenerateFlowFile处理器_ReplaceText处理器_实际操作---大数据之Nifi工作笔记0020
查看>>
NIFI大数据进阶_Json内容转换为Hive支持的文本格式_实际操作_02---大数据之Nifi工作笔记0032
查看>>
NIFI大数据进阶_Json内容转换为Hive支持的文本格式_操作方法说明_01_EvaluteJsonPath处理器---大数据之Nifi工作笔记0031
查看>>
NIFI大数据进阶_Kafka使用相关说明_实际操作Kafka消费者处理器_来消费kafka数据---大数据之Nifi工作笔记0037
查看>>
NIFI大数据进阶_Kafka使用相关说明_实际操作Kafka生产者---大数据之Nifi工作笔记0036
查看>>
NIFI大数据进阶_NIFI的模板和组的使用-介绍和实际操作_创建组_嵌套组_模板创建下载_导入---大数据之Nifi工作笔记0022
查看>>
NIFI大数据进阶_NIFI监控功能实际操作_Summary查看系统和处理器运行情况_viewDataProvenance查看_---大数据之Nifi工作笔记0026
查看>>
NIFI大数据进阶_NIFI监控的强大功能介绍_处理器面板_进程组面板_summary监控_data_provenance事件源---大数据之Nifi工作笔记0025
查看>>