Last active
May 3, 2018 09:24
-
-
Save JoolsF/083a18d084b582d47cf532668e33a8aa to your computer and use it in GitHub Desktop.
Lift function example 1
This file contains hidden or 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 | |
| // Allows a function A => B to operate on options | |
| def lift[A, B](f: A => B): Option[A] => Option[B] = _ map f //(a: Option[A]) => a.map(f) | |
| val cbrtO: Option[Double] => Option[Double] = lift(math.cbrt) | |
| val r1 = Try(throw new RuntimeException).toOption | |
| val r2 = Try(1000d).toOption | |
| cbrtO(r1) // res0: Option[Double] = None | |
| cbrtO(r2) // res1: Option[Double] = Some(10.0) | |
| // Another example | |
| def map2[A, B, C](a: Option[A], b: Option[B])(f: (A, B) => C): Option[C] = | |
| a.flatMap(aa => b.map(bb => f(a, b))) | |
| def bar(a: Int, b: Int) = a * b | |
| def foo(a: String, b: String): Option[Int] = { | |
| val aOpt: Option[Int] = Try(a.toInt).toOption | |
| val bOpt: Option[Int] = Try(b.toInt).toOption | |
| map2(aOpt, bOpt)(bar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment