Search code examples
scalatraversalscala-cats

Scala cats, traverse Seq


I know I can traverse Lists

import cats.instances.list._
import cats.syntax.traverse._

def doMagic(item: A): M[B] = ???
val list: List[A] = ???
val result: M[List[B]] = list.traverse(doMagic)

And I can convert a Seq back and forth to List

val seq: Seq[A] = ???
val result: M[Seq[B]] = seq.toList.traverse(doMagic).map(_.toSeq)

But can I also traverse Seq without the boilerplate?

val seq: Seq[A] = ???
val result: M[Seq[B]] = seq.traverse(doMagic)

Or what's an easy way to get an instance of Traverse[Seq]?


Solution

  • Cats does not provide typeclass instances for Seq, so besides implementing it yourself you're stuck with the conversion.

    As to why, there's an ongoing discussion in an (somewhat old) Cats issue. To sum it up, you won't know enough about Seq underlying characteristics to make sure some of the typeclasses instances laws hold.

    EDIT : Nevermind, it exists now, see linked thread