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

来源:互联网 发布:php 7.0 phpmyadmin 编辑:程序博客网 时间:2024/04/29 14:32

  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...


final class EitherOps[A](self: A) {

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

<p style="font-family: Arial, Helvetica, sans-serif; white-space: normal;"><span style="font-family:SimSun;font-size:14px;"></span></p>  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.rightb <- 2.right} yield a + b                                     //> epok1  : scalaz.\/[Nothing,Int] = \/-(5)val epno1 = for {a <- 3.rightc <- "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...


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

0 0
原创粉丝点击