我用过 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 forcats.Id
allows us to apply a functionA => B
to anId[A]
and get anId[B]
. However, anId[A]
is the same asA
, so all we're doing is applying a pure function of typeA => B
to a pure value of typeA
to get a pure value of typeB
. 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[_]
时,只需将这些实例用于更简单的情况。 (即,当 F
是 Id
时)。
关于scala - 为什么cats在评估Reader时返回 `Id[T]`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44872611/