
Thomas Hartman wrote:
I would be interested in seeing good motivating examples for use of the state monad... Okay, it's good for randomness. What else? ...I saw an example about using state to uniquely label elements of a tree So, are there any other simple motivating examples that show what state is really good for?
I find that there are two basic ways that the State monad is useful for me. One is when functions have an extra parameter, or a tuple return type, that is not really a natural part of the meaning of the function but is only there for keeping state. In those cases, a state monad makes the intention more clear. The examples you mentioned - random generators and tree labeling - are both of this type. This first use is especially helpful when there are several functions that all share the same state. The other use is for backtracking. In the monad StateT s [], the state is re-initialized to its original value for each item of the list. Here is a fully spelled out example: http://haskell.org/haskellwiki/Sudoku#Backtrack_monad_solver The first solver on that page, by Cale Gibbard, is a more elegant way to do the same thing without spelling out so explicitly all the details of how the monad is giving you the backtracking effect. A few other solvers also use a backtracking monad. Have fun, Yitz