博客
关于我
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/

你可能感兴趣的文章
Nginx配置静态代理/静态资源映射时root与alias的区别,带前缀映射用alias
查看>>
Nginx面试三连问:Nginx如何工作?负载均衡策略有哪些?如何限流?
查看>>
Nginx:NginxConfig可视化配置工具安装
查看>>
ngModelController
查看>>
ngrok | 内网穿透,支持 HTTPS、国内访问、静态域名
查看>>
ngrok内网穿透可以实现资源共享吗?快解析更加简洁
查看>>
NHibernate学习[1]
查看>>
NHibernate异常:No persister for的解决办法
查看>>
NIFI1.21.0_java.net.SocketException:_Too many open files 打开的文件太多_实际操作---大数据之Nifi工作笔记0051
查看>>
NIFI1.21.0_Mysql到Mysql增量CDC同步中_日期类型_以及null数据同步处理补充---大数据之Nifi工作笔记0057
查看>>
NIFI1.21.0_Mysql到Mysql增量CDC同步中_补充_更新时如果目标表中不存在记录就改为插入数据_Postgresql_Hbase也适用---大数据之Nifi工作笔记0059
查看>>
NIFI1.21.0_NIFI和hadoop蹦了_200G集群磁盘又满了_Jps看不到进程了_Unable to write in /tmp. Aborting----大数据之Nifi工作笔记0052
查看>>
NIFI1.21.0_Postgresql和Mysql同时指定库_指定多表_全量同步到Mysql数据库以及Hbase数据库中---大数据之Nifi工作笔记0060
查看>>
NIFI1.21.0最新版本安装_连接phoenix_单机版_Https登录_什么都没改换了最新版本的NIFI可以连接了_气人_实现插入数据到Hbase_实际操作---大数据之Nifi工作笔记0050
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表多表增量同步_增删改数据分发及删除数据实时同步_通过分页解决变更记录过大问题_02----大数据之Nifi工作笔记0054
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表多表增量同步_插入修改删除增量数据实时同步_通过分页解决变更记录过大问题_01----大数据之Nifi工作笔记0053
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表或全表增量同步_实现指定整库同步_或指定数据表同步配置_04---大数据之Nifi工作笔记0056
查看>>
NIFI1.23.2_最新版_性能优化通用_技巧积累_使用NIFI表达式过滤表_随时更新---大数据之Nifi工作笔记0063
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_根据binlog实现数据实时delete同步_实际操作04---大数据之Nifi工作笔记0043
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置binlog_使用处理器抓取binlog数据_实际操作01---大数据之Nifi工作笔记0040
查看>>