[Haskell-cafe] State Monad

Mark Carroll markc at chiark.greenend.org.uk
Wed Mar 2 22:12:05 EST 2005


On Thu, 3 Mar 2005, Sam G. wrote:

> I need a Monad to represent an internal stack. I mean I've got a lot
> of functions which operates on lists and I would not like to pass the
> list as an argument everytime.
> 
> Could you help me writing this monad? To start, I just need a +
> function which will return the sum of the 2 toppest elements of the
> stack.

I wrote one which is at,

http://www.aetion.com/src/Stack.hs
http://www.aetion.com/src/StackM.hs

Then,

add :: Num a => Stack a ()

add =
    do x <- pop
       y <- pop
       push (x + y)

or whatever.

Of course, if you use Control.Monad.State where you store the stack as a
list then you can probably just do something like,

add = (x:y:z) <- get
      put ((x+y):z)  

I hope that helps.

-- Mark



More information about the Haskell-Cafe mailing list