如何将Scala Cat's Kleisli与任何一种一起使用

KaC*_*KaC 2 scala either kleisli scala-cats

我正在尝试使用Kleisli编写返回monad的函数。它适用于Option:

import cats.data.Kleisli
import cats.implicits._

object KleisliOptionEx extends App {
  case class Failure(msg: String)
  sealed trait Context
  case class Initial(age: Int)                                   extends Context
  case class AgeCategory(cagetory: String, t: Int)                    extends Context
  case class AgeSquared(s: String, t: Int, u: Int)             extends Context

  type Result[A, B] = Kleisli[Option, A, B]
  val ageCategory: Result[Initial,AgeCategory] =
    Kleisli {
      case Initial(age) if age < 18 => {
        Some(AgeCategory("Teen", age))
      }
    }

  val ageSquared: Result[AgeCategory, AgeSquared] = Kleisli {
      case AgeCategory(category, age) =>  Some(AgeSquared(category, age, age * age))
    }

  val ageTotal = ageCategory andThen ageSquared
  val x = ageTotal.run(Initial(5))
  println(x)
}
Run Code Online (Sandbox Code Playgroud)

但是我无法使其与Either ...一起使用:

import cats.data.Kleisli
import cats.implicits._

object KleisliEx extends App {
  case class Failure(msg: String)

  sealed trait Context
  case class Initial(age: Int)                                   extends Context
  case class AgeCategory(cagetory: String, t: Int)                    extends Context
  case class AgeSquared(s: String, t: Int, u: Int)             extends Context

  type Result[A, B] = Kleisli[Either, A, B]

  val ageCategory: Result[Initial,AgeCategory] =
    Kleisli {
      case Initial(age) if age < 18 => Either.right(AgeCategory("Teen", age))
    }

  val ageSquared : Result[AgeCategory,AgeSquared] = Kleisli {
      case AgeCategory(category, age) =>  Either.right(AgeSquared(category, age, age * age))
    }

  val ageTotal = ageCategory andThen ageSquared
  val x = ageTotal.run(Initial(5))

  println(x)
}
Run Code Online (Sandbox Code Playgroud)

我猜每个都有两个类型参数,一个Kleisle包装器需要一个输入和一个输出类型参数。我不怎么向Either隐藏左类型...

Den*_*sca 5

正如您正确指出的那样,问题是这样的事实:它Either接受两个类型参数,而Kleisli期望一个仅接受一个类型构造函数。我建议您看看可以解决您问题的kind-projector插件。

您可以通过几种方式解决此问题:

如果中的错误类型Either始终相同,则可以执行以下操作:

    sealed trait MyError
    type PartiallyAppliedEither[A] = Either[MyError, A]
    type Result[A, B] = Kleisli[PartiallyAppliedEither, A, B]
    // you could use kind projector and change Result to
    // type Result[A, B] = Kleisli[Either[MyError, ?], A, B]
Run Code Online (Sandbox Code Playgroud)

如果错误类型需要更改,则可以使您的Result类型采用3个类型参数,然后采用相同的方法

type Result[E, A, B] = Kleisli[Either[E, ?], A, B]
Run Code Online (Sandbox Code Playgroud)

请注意?来自kind-projector