Last active
November 13, 2018 23:13
-
-
Save velppa/e92eab1a721aa913ddea4a65b80b8926 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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