SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
25.
FlatMap Power
1 val ab: Service[A, B] = ???
2 val bc: Service[B, C] = ???
3 val cd: Service[C, D] = ???
4
5 val req: A = ???
6 val rep: Future[D] = ab(req) flatMap bc flatMap cd
25
26.
Sequential Composition: map & flatMap
1 object FlatMapFibonacciCalculator extends FibonacciCalculator {
2 def calculate(n: BigInt): Future[BigInt] =
3 if (n == Zero || n == One) Future.value(n)
4 else calculate(n - One) flatMap { a =>
5 calculate(n - Two) flatMap { b => Future.value(a + b) }
6 }
7 }
8
9 object MapFibonacciCalculator extends FibonacciCalculator {
10 def calculate(n: BigInt): Future[BigInt] =
11 if (n == Zero || n == One) Future.value(n)
12 else calculate(n - One) map { a =>
13 calculate(n - Two) map { b => a + b }
14 }
15 }
26
27.
Sequential Composition: for-comprehension
1 object ForFibonacciCalculator extends FibonacciCalculator {
2 def calculate(n: BigInt): Future[BigInt] =
3 if (n == Zero || n == One) Future.value(n)
4 else for {
5 a <- calculate(n - One)
6 b <- calculate(n - Two)
7 } yield a + b
8 }
27