Going a bit further in Functional Programming concepts with Traversable
We already saw a few concepts so far such as Functor
and Applicative
.
Let's dig deeper !
Traversable solves a specific problem. How to apply an operation to many inputs at once without leaving the “Box/Container/F” ?
Without Traversable, we would have to perform something like this:
val input: List[Int] = List(1,2,3)
val operation: Int => F[Int] = ???
val output: List[F[Int]] = input.map( i => operation(i))
But how do we manage to get F[List[A]]
instead of List[F[A]]
? Traversable !
To implement traverse
we re-use what we built in the previous episodes: Functor
and Applicative
. So we can chain the operation and wrap into F
.
With traverse
which allows you to apply an operation to many element and stay inside F
, we also get for free sequence
which allow you to flip List[F[A]]
inside out into F[List[A]]
. You will see it in Future.sequence
for instance that is very convenient to wait or combine many Future
together.
As a note: input.map(f).sequence
is the same as input.traverse(f)
.