从Scala中的函数编程,我正在尝试实现Either.map。
trait Either[+E, +A] {
def map[B](f: A => B): Either[E, B] = this match {
case Either(x: E, y: A) => Right(f(y))
case _ => Left()
}
}编译时会出现一个错误,包括其他错误。我没有给他们看,因为我似乎错过了实现Either.的概念
Either.scala:3: error: value Either is not a case class constructor,
nor does it have an unapply/unapplySeq method
case Either(x: E, y: A) => Right(f(y))请建议我如何实施它。
发布于 2013-09-12 04:57:06
错误消息指出,不能将Either用作case类构造函数。IOW,Either等同于抽象类,因为您已经用自己的可实现方法将它编码为一个特性。让我们假设您有以下Either、Left和Right的编码表示
sealed trait Either[+E, +A] {
def map[B](f: A => B): Either[E, B] = ???
}
// Left signifies error condition
// Right is something Right, along with its message.
case class Left[+E](err: E) extends Either[E,Nothing]
case class Right[+E](msg: E) extends Either[Nothing,E]您可以将map函数编写为:
def map[B](f: A => B): Either[E, B] = this match {
case Right(v) => Right(f(v))
case Left(e) => Left(e)
}这里我只是简单地说,如果您遇到了一些应该是正确的值,那么对它执行一些函数计算,并按它应有的方式返回它--一个Right。因为Either是一个sealed trait(主要是为了方便起见),所以唯一的其他类型可能是一个Left,我按原样返回它。Either
发布于 2013-09-12 01:47:36
试试这个
trait Either[+E, +A] {
def map[B](f: A => B): Either[E, B] = this match {
case Right(y) => Right(f(y))
case left: Left[E] => left
}
}https://stackoverflow.com/questions/18754013
复制相似问题