如何在 Kotlin/Arrow 中调用依赖于多个类型类的多态函数

How to call a polymorphic function which depends on multiple Typeclasses in Kotlin/Arrow

我创建了一个函数,该函数在它需要使用的 Monad 中是多态的,而不是依赖于此 Monad 存在的类型类实例。它看起来像这样:

fun <M> M.logic(...): Kind<M, String>
      where M: MonadReader<M, Dependency>,
            M: Effect<M> =
   fx.monad() {
      val dependency = ask().bind()
      val response = effect { ...using dependency here... }.bind()
      response
   }

我正在使用 MonadReader 来获得依赖性,我正在使用 Effect,好吧,为了效果。现在我假设,我所需要的只是使用一些 Monad Transformer 来获得这个 Monad "at the end of the world" 的星座(即在 main() 中)。类似于 ReaderT<ForIO, Dependency, Unit>.

但是,我似乎无法创建合适的 M(或任何上下文)来调用此方法。如何在具有必要类型类实例的精确 monad 上调用此方法?

这是您要查找的代码片段:

fun <M, F> M.logic(): Kind<F, String>
  where M: MonadReader<F, String>,
        M: Async<F> =
  fx.monad {
    val dependency = ask().bind()
    val response = effect { dependency }.bind()
    response
  }

object Transformer: 
  Async<KleisliPartialOf<ForIO, String>> by ReaderT.async(IO.effect()),
  KleisliMonadReader<ForIO, String> by ReaderT.monadReader(IO.monad())

请注意,Async 是您所追求的,而不是命名不当的 Effect。并且您需要两个泛型,一个用于组合,另一个用于内容。

Transformer.run {
  logic()
}

Reader 的异步实例已于 2020 年 1 月添加,并将在下一个版本 0.10.5 或 0.11.0 中提供:https://github.com/arrow-kt/arrow/commit/6aaae6998de612eb0eec948697f1c477649230be