The meaning of Reader and State is expressed by their definition. Therefore by showing their definition, we can clearly understand what they mean to do.
abbrev Reader r a := r -> a
abbrev State s a := s -> (s, a)
Reader is meant to return a value of a
, given an environment of r
, that is, a value of a
can be derived from an environment of r
.
State is meant to return a value of a
and a new environment of s
, given an environment of s
, that is, given an environment of s
, it will return a value of a
, and a changed environment of s
at the same time.
The key meaning of Reader and State abstraction is showed above. Next, I will demonstrate the implementation of Monad behavior of them.
instance Monad (Reader r) where
pure: a -> Reader r a := fun x: a => fun env: r => x
bind: Reader r a -> (a -> Reader r b) -> Reader r b
:= fun ra: Reader r a =>
fun fa: a -> Reader r b =>
fun env: r => fa (ra env) env
instance Monad (State s) where
pure: a -> State r a := fun x: a => fun env: r => (x, env)
bind: State r a -> (a -> State r b) -> State r b
:= fun ra: State r a =>
fun fa: a -> State r b =>
fun env: r =>
let (a, env') = ra env in fa a env'
From above Monad behavior implementations for Reader and State, we can see that, the environment of Reader is immutable, it is provided unchangedly for later processing, whereas the environment of State is mutable, which may be modified by later processing.