Commit 75a42c3e authored by Haochen Xie's avatar Haochen Xie

add ch4/Option.scala

parent 95d5724a
package name.haochenxie.fpscala.ch4
sealed trait Option[+A] {
// Exercise 4.1 (A)
def flatMap[B](f: A => Option[B]): Option[B] = this match {
case None => None
case Some(v) => f(v)
}
// Exercise 4.1 (B)
def map[B](f: A => B): Option[B] = flatMap(v => Some(f(v)))
// Exercise 4.1 (C)
def getOrElse[B >: A](default: => B): B = this match {
case None => default
case Some(v) => v
}
// Exercise 4.1 (D)
def orElse[B >: A](ob: => Option[B]): Option[B] = this match {
case None => ob
case $@_ => $
}
// Exercise 4.1 (E)
def filter(pred: A => Boolean): Option[A] =
flatMap(v => if (pred(v)) Some(v) else None)
}
case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]
object Option {
def lift[A,B](f: A => B): Option[A] => Option[B] = _.map(f)
def Try[A](a: => A): Option[A] =
try Some(a)
catch { case e: Exception => None }
// Exercise 4.3
def map2[A,B,C](oa: Option[A], ob: Option[B])(f: (A, B) => C): Option[C] =
oa.flatMap(a => ob.map(b => f(a, b)))
// Exercise 4.4
def sequence[A](oas: List[Option[A]]): Option[List[A]] = oas match {
case Nil => Some(Nil)
case None :: tail => None
case Some(a) :: tail => sequence(tail).map(a :: _)
}
// Exercise 4.5
def traverse[A,B](as: List[A])(f: A => Option[B]): Option[List[B]] = as match {
case Nil => Some(Nil)
case a :: as => traverse(as)(f).flatMap(bs => f(a).map(b => b :: bs))
}
}
object OptionScratch {
// Exercise 4.2 (A)
def mean(xs: Seq[Double]): Option[Double] = {
if (xs.isEmpty) None
else Some(xs.sum / xs.size)
}
// Exercise 4.2 (B)
// since the success of mean guarantee the positiveness of xs.length,
// we don't actually need flatMap here..
def variance(xs: Seq[Double]): Option[Double] = {
mean(xs)
.map(mean => xs.map(x => Math.pow(x - mean, 2)).sum)
.map(_ / xs.size)
.map(Math.pow(_, 0.5))
}
def main(args: Array[String]) {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment