Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]?

like image 254
Victor Basso Avatar asked Feb 16 '18 13:02

Victor Basso


2 Answers

As of cats 2.3, support for immutable.Seq is now built in. See "Where are implicit instances for Seq?" on the FAQ or this PR where the functionality was added.

like image 77
Cory Klein Avatar answered Nov 08 '22 04:11

Cory Klein


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

like image 6
LMeyer Avatar answered Nov 08 '22 02:11

LMeyer