[英]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.