Scala函数式编程课后习题答案(第四章)(更新ing)

来源:互联网 发布:数据的标准化的公式 编辑:程序博客网 时间:2024/06/06 16:29

Scala函数式编程课后习题答案(第四章)(更新ing)

练习4.1

trait Option[+A] {  case object None extends Option[Nothing]  case class Some[+A](value:A) extends Option[A]  def map[B](f: A => B): Option[B]= this match {    case None => None    case Some(a) => Some(f(a))  }  def flatMap[B](f:A=>Option[B]):Option[B] = this match {    case None => None    case Some(a) => f(a)  }  def getOrElse[B>:A](default: => B):B = this match {    case None => default    case Some(a) => a  }  def orElse[B>:A](ob: => Option[B]):Option[B] = this match {    case None => ob    case _ => this  }  def filter(f:A =>Boolean):Option[A] = this match {    case Some(a) if (f(a)) => this    case _ => None  }}
0 0
原创粉丝点击