简体   繁体   English

在Scalaz中,Kleisli,ReaderT和Reader是否相同只是巧合

[英]Is it just a coincidence that Kleisli, ReaderT, and Reader are the same in Scalaz

In Scalaz 在斯卡拉兹

  • Kleisli[F, A, B] is a wrapper for A => F[B] . Kleisli[F, A, B]A => F[B]的包装器。
  • ReaderT[F, A, B] -- reader monad transformer -- is just an alias of Kleisli[F, A, B] . ReaderT[F, A, B] - 读者monad变换器 - 只是Kleisli[F, A, B]的别名。
  • Reader[A, B] monad is a specialization of ReaderT with identity monad Id : Reader[A, B] monad是ReaderT的专业化,具有身份monad Id
    type Reader[A, B] = ReaderT[Id, A, B] . type Reader[A, B] = ReaderT[Id, A, B]

Is it just a coincidence or there are some deeper reasons that Kleisli , ReaderT , and Reader are isomorphic in Scalaz ? 这只是一个巧合还是有一些更深层次的原因, KleisliReaderTReader在Scalaz中是同构的?

You can think of it as arriving at the same place by two different routes. 您可以将其视为通过两条不同的路线到达同一个地方。 On one side you start with the reader monad, which is simply a kind of wrapper for functions. 一方面,你从阅读器monad开始,它只是一种函数包装器。 Then you realize that you want to integrate this reader functionality into a larger monad with other "effects", so you create a ReaderT monad transformer. 然后你意识到你想要将这个阅读器功能集成到一个带有其他“效果”的更大的monad中,所以你创建了一个ReaderT monad变换器。 At that point it makes sense to implement your original Reader[E, ?] as ReaderT[Id, E, ?] . 那时将原始Reader[E, ?] ReaderT[Id, E, ?] Reader[E, ?]ReaderT[Id, E, ?] Reader[E, ?]ReaderT[Id, E, ?]

From the other side, you want a type to represent Kleisli arrows (ie functions with a monadic return type). 另一方面,您需要一个类型来表示Kleisli箭头(即具有monadic返回类型的函数)。 It turns out that this is the same thing as ReaderT , so you just make that an alias. 事实证明这与ReaderT是一样的,所以你只需ReaderT它作为别名。

There's nothing terribly mysterious about the "it turns out" part. 关于“结果”部分,没有什么可怕的神秘感。 It's a little like if you started out with an Addable type class for number-like things, then decide to make it more generic, and eventually end up with a type class that just provides an associative "addition-like" operation. 这有点像你开始使用Addable数字的Addable类型的东西,然后决定使它更通用,并最终得到一个类型类,它只提供一个关联的“类似添加”操作。 You've reinvented Semigroup ! 你重塑了Semigroup You may still want to keep the Addable name around, though, for historical or pedagogical reasons, or just for convenience. 但是,出于历史或教学原因,或者仅仅是为了方便起见,您可能仍希望保留可Addable名称。

That's all that's happening with Reader and ReaderT —you don't need these aliases, but they can be convenient, and may help improve the clarity of your code. 这就是ReaderReaderT发生的一切 - 你不需要这些别名,但它们可以很方便,并且可以帮助提高代码的清晰度。

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

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