So... it's a monad? I don't understand why this is worth calling State as distinct from non-State when that doesn't seem to add any meaning. Surely there must be something implied by a State monad that is not implied by a non-State monad. That seems relevant to call out in an introduction.
See this is what I'm talking about. What does `state` mean to you where monads don't have any relation? It's just an abstract structure—what makes something state or not is the context.
How do I think of the State monad?
- Like a Mealy machine: https://en.wikipedia.org/wiki/Mealy_machine
- Like a pure way to compose functions that use a nameless, global mutable variable.
- As a newtype wrapper over the type "s -> (a, s)" where s is the type of the state and a is the type of the computation.
For example, this is a really minimalistic arithmetic syntax tree interpreter in Haskell. You could write errors using the Either type:
It's cumbersome, and there's a staircase growing. Because Either is a monad, you could rewrite the division op like this: This is a good article about the either monad: https://mmhaskell.com/blog/2022/3/3/using-either-as-a-monadThe state monad is basically a wrapper over a pure function that takes a state and returns a tuple with the result and a new state. In an imperative language, you'd just actually change state, rather than doing that.
An example from this wiki page: https://en.wikibooks.org/wiki/Haskell/Understanding_monads/S...
In an imperative language, for pseudo-random numbers, you could modify global variables every time you want a new random number. Haskell lets you do this in IO functions. But a pure way would be to return the result of the new global variable every time.
It's annoying. You could use the state monad to simplify this: