List of Claysley in Claysley from the list

I was wondering if there is a way to turn List[Kleisli[Option, Int, Int]]into Kleisli[Option, Int, List[Int]].

In particular, I have a kleisli list formed as follows:

def k(a: String) = Kleisli[Option, Int, Int](m => Some(a.length * m))
val kList = List("hi", "hello").map(k)

I do the following

Kleisli[Option, Int, List[Int]](m => kList.map(_.run(m)).sequence)

which is very dirty, not expressive and requires a lot of manual work.

Is there a better way?

+4
source share
3 answers

Yes, you can use traversethat does just that. If you use cats<= 0.9.0, you can use the following code:

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

// ...
def k(a: String) = Kleisli[Option, Int, Int](m => Some(a.length * m))
val result: Kleisli[Option, Int, List[Int] = List("hi", "hello").traverseU(k)

If you use Scala 2.11.9+ by adding scalacOptions += "-Ypartial-unification"to your file build.sbt, you can simply use traverseinstead traverseU. In addition, starting with version 1.0.0, traverseUand sequenceUwill no longer exist.

, Scala < 2.11.9, >= 2.10.6 , .

+6

- partial-unification traverse:

import cats.implicits._

List("hi", "hello").traverse(k)

, sequence kList, traverse map, sequence.

partial-unification - sbt-partial-unification .

Scala 2.11.9 , :

scalacOptions += "-Ypartial-unification"

cats , .

+4

TraverseOps.sequence, List[A[B]] A[List[B]],

A = ({type λ[α] = Kleisli[Option, Int, α]})
B = Int

, :

def transform(x: List[Kleisli[Option, Int, Int]]) =
  x.sequence[({type λ[α] = Kleisli[Option, Int, α]})#λ, Int]

- :

import scalaz._
import Scalaz._
import scalaz.Kleisli._

def transform(x: List[Kleisli[Option, Int, Int]]) = x.sequence[({type λ[α] = Kleisli[Option, Int, α]})#λ, Int]

def k(a: String) = Kleisli[Option, Int, Int](m => Some(a.length * m))
val kList = List("hi", "hello").map(k)
val res = transform(kList)
res.run(10)

https://scastie.scala-lang.org/2uZvWWb1ScOHNA55QOcWQA

+2

Source: https://habr.com/ru/post/1687471/