On Thu, 2005-03-03 at 02:03 +0100, 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.
>
> Thanks in advance,
> Sam.
Here's a little program for you to ponder over.
Cheers,
Bernie.
import Control.Monad.State
type Stack a = [a]
push :: a -> Stack a -> Stack a
push x s = x:s
peek :: Stack a -> Maybe a
peek (x:_) = Just x
peek other = Nothing
multTopTwo :: Num a => Stack a -> Stack a
multTopTwo (x:y:rest)
= x * y : rest
multTopTwo other = other
type StateStack a = State (Stack Int) a
pushList :: [Int] -> StateStack ()
pushList [] = return ()
pushList (x:xs)
= (modify $ push x) >> pushList xs
prog :: [Int] -> StateStack (Maybe Int)
prog xs
= do pushList xs
modify multTopTwo
gets peek
main = print $ evalState (prog [1..5]) []
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe