Skip to Content
Mastering Functional Programming
book

Mastering Functional Programming

by Anatolii Kmetiuk
August 2018
Intermediate to advanced
380 pages
10h 2m
English
Packt Publishing
Content preview from Mastering Functional Programming

The computation

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781788620796Supplemental Content