繁体   English   中英

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

[英]How to use Scala Cats' Kleisli with Either

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

但是我无法使其与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隐藏左类型...

正如您正确指出的那样,问题是这样一个事实: 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM