Just learning about State monad from this excellent tutorial. However, when I tried to explain it to a non-programmer they had a question that stumped me.
If the purpose of the State is to simulate mutable memory, why is the function that state monad stores is of the type:
s -> (a, s)
and not simply:
s -> s
In other words, what is the need for the “intermediate” value? For example, couldn’t we, in the cases where we need it, simulate it by simply defining a state as a tuple of (state, value)?
I’m sure I confused something, any help is appreciated.
To draw a parallel with an imperative language like C,
s -> scorresponds to a function with the return typevoid, which is invoked purely for side effects (such as mutating the memory). It is isomorphic toState s ().And indeed, it is possible to write C functions which communicate only through global variables. But, as in C, it is often convenient to return values from functions. That’s what
ais for.Of course it’s possible that for your particular problem
s -> sis a better choice. Although it’s not a Monad, it is a Monoid (when wrapped in Endo). So you can construct such functions using<>andmempty, which correspond to>>=andreturnof Monad.