您的位置:首页 > 编程语言

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

2017-05-15 15:01 676 查看

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
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: