<html><body><div>I am trying to relate the state monad to a stack example and somehow found it easy to get recursively confused!</div><div><br></div><div>instance Monad (State s) where</div><div>    return x = State $ \s -> (x,s)</div><div>    (State h) >>= f = State $ \s -> let (a, newState) = h s</div><div>                                                    (State g) = f a</div><div>                                                     in g newState</div><div><br></div><div>Considering the stack computation</div><div><br></div><div>stackManip stack = let </div><div>              ((), newStack1) = push 3 stack</div><div>              (a, newStack2) = pop newStack1</div><div>               in pop newStack2</div><div><br></div><div>in do notation this would become </div><div>do  </div><div>   push 3  </div><div>   a <- pop  </div><div>   pop</div><div><br></div><div>If I consider the first computation push 3 >>= pop and try to translate it to the definition there are problems....</div><div>Copy paste again, I have </div><div><div>    (State h) >>= f = State $ \s -> let (a, newState) = h s</div><div>                                                    (State g) = f a</div><div>                                                     in g newState</div></div><div><br></div><div>f is the push function to which we are shoving the old state. I can't exactly get around to what exactly is the state computation h? Ok assuming it's something which gives me a new state, but then thats push which is function f. </div><div>Then push is applied to a which is assuming 3 in this case. This gives me a new state, which I would say newStack1 from the stockManip above.</div><div><br></div><div>Then somehow I apply g to newState?? All the more confusion. Back to the question what exactly is state computation and how is it different from f? It seems to be the same function?</div><div><br></div><div><br></div><div>-Animesh</div><div><br></div><div><br></div><div><br></div><div><br></div><div>                           </div></body></html>