Scala Traversable

Going a bit further in Functional Programming concepts withTraversable

We already saw a few concepts so far such asFunctorandApplicative.
Let's dig deeper !

Traversablesolves a specific problem. How to apply an operation to many inputs at once without leaving the “Box/Container/F” ?

WithoutTraversable, 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 getF[List[A]]instead ofList[F[A]]? Traversable !

To implementtraversewe re-use what we built in the previous episodes:FunctorandApplicative. So we can chain the operation and wrap intoF.

Withtraversewhich allows you to apply an operation to many element and stay insideF, we also get for freesequencewhich allow you to flipList[F[A]]inside out intoF[List[A]]. You will see it inFuture.sequencefor instance that is very convenient to wait or combine manyFuturetogether.

As a note:input.map(f).sequenceis the same asinput.traverse(f).

Reveal more information and clues
Load Exercise