I was wondering if there is a way to turn List[Kleisli[Option, Int, Int]] to Kleisli[Option, Int, List[Int]].
In particular I have the list of kleisli formed like this:
def k(a: String) = Kleisli[Option, Int, Int](m => Some(a.length * m))
val kList = List("hi", "hello").map(k)
What I do is the following
Kleisli[Option, Int, List[Int]](m => kList.map(_.run(m)).sequence)
which is very messy, not expressive and requires a lot of manual work.
Is there a better way?
Yes, you can use
traversewhich does just that. If you're usingcats<= 0.9.0 you can use the following code:If you're using Scala 2.11.9+, by adding
scalacOptions += "-Ypartial-unification"to yourbuild.sbtfile, you can just usetraversein place oftraverseU. Also, starting from version 1.0.0,traverseUandsequenceUwill no longer exist.Note that, if you're using Scala < 2.11.9 but >= 2.10.6 you can still enable partial unification by adding this plugin to your build.