scala - 为什么cats在评估Reader时返回 `Id[T]`?

标签 scala functional-programming monads scala-cats

我用过 Kleisli之前和,当您评估将依赖项传递给它的计算时,monad 返回我需要的值。
现在我正在使用 Reader我看到当我运行程序时,评估返回包装在 Id 中。 .

为什么?

此外,探索 Id 的不同选项我遇到过 init解包计算值的函数。使用那个“组合器”好不好?我唯一需要的东西来自 Reader是没有任何包装的生产值。

谢谢

最佳答案

Id定义为 type Id[A] = A .所以它只是类型本身,你可以像没有 Id 一样使用它。那里。

以下代码有效:

val s: Id[String] = "123"
s.charAt(s.length - 1) 

cats文件指出:

Identity, encoded as type Id[A] = A, a convenient alias to make identity instances well-kinded.

The identity monad can be seen as the ambient monad that encodes the effect of having no effect. It is ambient in the sense that plain pure values are values of Id.

For instance, the cats.Functor instance for cats.Id allows us to apply a function A => B to an Id[A] and get an Id[B]. However, an Id[A] is the same as A, so all we're doing is applying a pure function of type A => B to a pure value of type A to get a pure value of type B. That is, the instance encodes pure unary function application.



例如,对于 Reader将其定义为更方便:
type Reader[A, B] = ReaderT[Id, A, B]
type ReaderT[F[_], A, B] = Kleisli[F, A, B]

这允许您在 F[_] 时为更复杂的情况定义所有类型类实例。是真实的,当没有 F[_] 时,只需将这些实例用于更简单的情况。 (即,当 FId 时)。

关于scala - 为什么cats在评估Reader时返回 `Id[T]`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44872611/

相关文章:

scala - 如何将 Map 值转换为 Scala 中的集合

scala - 使用 Scala Either,如何在第一个错误处停止,但获取已经计算的值

python - 是否可以根据不同的输入信息创建函数?

haskell - IO monad 中的函数组合

haskell - monad 中的纯映射

Haskell State Monad 和 Binary 不输出所有内容

scala - Play和Scala的依赖注入(inject)框架?

scala - 无法从 Spark 连接到 Cassandra(接触点包含多个数据中心)

javascript - 有没有更好的方法在 JavaScript 中对数组项进行部分求和?

haskell - 如何解释函数实例的bind/>>=?