【问题标题】:How to use Scala Cats' Kleisli with Either如何将 Scala Cats 的 Kleisli 与 Either 一起使用
【发布时间】:2018-10-01 01:37:37
【问题描述】:

我正在尝试使用 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)
}

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

【问题讨论】:

    标签: scala scala-cats either kleisli


    【解决方案1】:

    正如您正确陈述的那样,问题在于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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2018-02-09
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 2019-10-09
      相关资源
      最近更新 更多