August 2018
Intermediate to advanced
380 pages
10h 2m
English
Suppose that you have some long-running competition. Suppose that the computation in question has the task of finding a sum of numbers on a specific range. The computation is long-running because the invocation must pause for half a second from number to number:
def sum(from: Int, to: Int): IO[Int] = Monad[IO].tailRecM((from, 0)) { case (i, runningTotal) => if (i == to) IO.pure( Right(runningTotal + i) ) else if (i > to) IO.pure( Right(runningTotal) ) else for { _ <- IO { println(s"${Thread.currentThread.getName}: " + s"Running total from $from to $to, currently at $i: $runningTotal") } _ <- IO.sleep(500 milliseconds) } yield Left((i + 1, runningTotal + i)) }
We are defining our competition in terms of a Monadic loop. In the ...