如何使用Scala Cats' Kleisli与Either

时间:2018-04-20 10:45:20

标签: scala scala-cats either kleisli

我试图使用Kleisli来编写返回monad的函数。它适用于选项:

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)
}

但是我不能让它与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)
}

我猜要么有两个类型参数,而Kleisle包装器需要一个输入和一个输出类型参数。我不知道如何隐藏Either中的左侧类型......

1 个答案:

答案 0 :(得分: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]

如果需要更改错误类型,您可以改为使用Result类型取3类型参数,然后按照相同的方法

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

请注意?来自kind-projector