Skip to content

Instantly share code, notes, and snippets.

@velppa
Last active November 13, 2018 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velppa/e92eab1a721aa913ddea4a65b80b8926 to your computer and use it in GitHub Desktop.
Save velppa/e92eab1a721aa913ddea4a65b80b8926 to your computer and use it in GitHub Desktop.
import scala.util.Try
case class Triangle(
opposite: Float,
adjacent: Float,
hypotenuse: Float
) {
require(
opposite + adjacent > hypotenuse &&
adjacent + hypotenuse > opposite &&
opposite + hypotenuse > adjacent,
"Triangle's law should be satisfied")
require(
opposite*opposite + adjacent*adjacent == hypotenuse*hypotenuse,
"Pythagoras law should be satisfied")
def sin(): Option[Float] = {
hypotenuse match {
case 0 => None
case h => Some(opposite/h)
}
}
def cos(): Option[Float] = {
hypotenuse match {
case 0 => None
case h => Some(adjacent/h)
}
}
def tan(): Option[Float] = for {
s <- sin
c <- cos
} yield s/c
}
val good = Try(Triangle(3, 4, 5)).toOption
// good: Option[Triangle] = Some(Triangle(3.0,4.0,5.0))
println(good.flatMap(_.cos))
// Some(0.8)
println(good.flatMap(_.tan))
// Some(0.75)
val bad = Try(Triangle(4, 5, 5)).toOption
// bad: Option[Triangle] = None
println(bad.flatMap(_.cos))
// None
println(bad.flatMap(_.tan))
// None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment