Looking at the State Monad's wiki, I'm trying to understand the runState
and put
functions.
As I understand runState
, it takes a first argument of State
, which has a "universe", s
, and a value, a
. It takes a second argument of a universe. Finally, it returns a (a, s)
where a
is the new value and s
is the new universe?
ghci> :t runState
runState :: State s a -> s -> (a, s)
Example:
ghci> let s = return "X" :: State Int String
ghci> runState s 100
("X",100)
However, I'm don't understand the put
result:
ghci> runState (put 5) 1
((),5)
Since runState
returns an (a, s)
, why is the a
of type ()
?
I'm not confident on my above attempted explanations. Please correct me, and answer my question on put
.
The easiest way to really understand
State
, IMHO, is just to study the code and understand it well enough that you can implement it from memory, like I'm about to do:That really is just arbitrary/conventional. Taking the above as a baseline, we could just as well write
modify
,get
andput
like this:In this version
modify
andput
have the same effects as the original, but additional produce the old state as their result. Clients that usemodify
andput
only for the effect would not generally notice the difference.Alternatively, the "return old state" versions of
modify
andput
can be written in terms of the official ones. For example:So most of these operations are interdefinable, it doesn't much matter which ones are "basic" and which ones not...