Search code examples
scalazscala-catscats-effectzio

IO Monad vs Reader Monad


I wonder is there any relation between IO Monad and the Reader monad ?

Can the Environment in the Reader monad be an effect ? If so, how does ZIO or Cats IO, scalaz-effects deal with Reader Monad principles ?


Solution

  • The environment in a Reader is usually not an effect - it doesn't need to be.

    To understand why, you first need to understand that the Reader monad is an abstraction over functions A => B, where A is some kind of environment.

    In general, if you have an effect F[A], you can always map the value using the Reader's apply - function, right?

    For cats-effect, a Reader is simply defined as a Kleisli (an abstraction over functions A => F[B]) with F[_] being defined as type F[A] = A. Kleisli provides everything you need in terms of composition, which is why Reader's were defined to be a subset of Kleislis. You can read more about it here.

    For ZIO, things look a a little different.

    Take a look at the definition: ZIO[R, E, A]. These three type parameters describe the environment (R), the error type (E) and the result type (A).

    This means that ZIO is already a combination of the IO and Reader monads. In ZIO, you can access the environment using the access- function.