Alex Rivera | Logout

Why does State need a value?

Asked 2012-07-20T16:34:32.000
14

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.

Edit
Report

1 Answer

18

To draw a parallel with an imperative language like C, s -> s corresponds to a function with the return type void, which is invoked purely for side effects (such as mutating the memory). It is isomorphic to State 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 a is for.

Of course it's possible that for your particular problem s -> s is a better choice. Although it's not a Monad, it is a Monoid (when wrapped in Endo). So you can construct such functions using <> and mempty, which correspond to >>= and return of Monad.

answered 2012-07-20T16:57:36.623

Your Answer