Skip to content
This repository has been archived by the owner on Aug 1, 2018. It is now read-only.

Commit

Permalink
Merge pull request #27 from loustler/chapter4
Browse files Browse the repository at this point in the history
Add solution for exercise 4.2
  • Loading branch information
loustler authored Nov 5, 2017
2 parents 21ad6fa + 4afa130 commit 4491742
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/main/scala/com/chobostudy/loustler/error/Option.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,7 @@ trait Option[+A] {

case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]

object Option {
def apply[T](t: T): Option[T] = if (t == null) None else Some(t)
}
24 changes: 24 additions & 0 deletions src/main/scala/com/chobostudy/loustler/error/SolutionP68.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.chobostudy.loustler.error

import com.chobostudy.loustler.error.Option

/**
* @author loustler
* @since 11/03/2017 21:19
*/
trait SolutionP68 {
def mean(xs: Seq[Double]): Option[Double] = {
Option(xs.sum / xs.size)
}

// exercise 4.2
def variance(xs: Seq[Double]): Option[Double] = {
Option(xs).flatMap(x => {
val meanV = mean(xs).getOrElse(0.0)

mean(xs.map(d => math.pow(meanV - d, 2)))
})
}
}

object SolutionP68 extends SolutionP68
20 changes: 20 additions & 0 deletions src/test/scala/com/chobostudy/loustler/error/SolutionP68Test.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.chobostudy.loustler.error

import org.scalatest.FunSuite

/**
* @author loustler
* @since 11/03/2017 21:52
*/
class SolutionP68Test extends FunSuite {
test("variance should be correct") {
val seq = List(1.0, 1.1, 1.2, 1.3, 1.4)
val mean = seq.sum / seq.size
val variance = seq.map(d => Math.pow(mean - d, 2)).sum / seq.size
val expect = Option(variance)

val result = SolutionP68.variance(seq)

assert(result == expect)
}
}

0 comments on commit 4491742

Please sign in to comment.