Exercise 4.6 Right値を操作するmap,flatMap,orElse,map2をEitherに追加せよ
map2については内包表記を使うと簡潔になる
import scala.{Option => _, Either => _, _}
object Main {
def main(args:Array[String]) = {
val x=Right(1)
val y=Left(22)
println( x.map(i=>i*2))
println(x.flatMap(i=>Right(i)))
println(x.orElse(Left(999)))
println(y.orElse(Left(999)))
println(x.map2(Right(2))((a,b)=>a+b))
}
}
sealed trait Either[+E,+A] {
def map[B](f:A=>B):Either[E,B] = this match {
case Left(e) => Left(e)
case Right(a) => Right(f(a))
}
def flatMap[EE>:E,B](f:A=>Either[EE,B]):Either[EE,B] = this match {
case Left(e) => Left(e)
case Right(a) => f(a)
}
def orElse[EE >: E, AA >: A](b: => Either[EE, AA]): Either[EE, AA] = this match {
case Left(e) => b
case a => a
}
def map2[EE>:E,B,C](b:Either[EE,B])(f:(A,B)=>C):Either[EE,C] =
for { a <- this; b1 <- b } yield f(a,b1)
}
case class Left[+E](get: E) extends Either[E,Nothing]
case class Right[+A](get: A) extends Either[Nothing,A]
0 件のコメント:
コメントを投稿