[Haskell-beginners] State and Maybe and monad transformers

Andrew Bernard andrew.bernard at gmail.com
Wed Sep 30 04:22:21 UTC 2015


Greetings All,

I am writing code using a BankersDequeue from Data.Dequeue. I’d like to wrap the push and pop operations in a state monad for the standard reason, to avoid passing the dequeue around between function calls, and regard it as state instead, which it is. Wishing to avoid throwing a runtime error if the queue is empty (for the general case of queues) I have written a reduction of the concept using a crude stack to experiment, which uses State and Maybe. I notice that there are very few examples of using State and Maybe together. My questions are: Is this a faulty design pattern? Should this be done with monad transformers? Are there examples to be found of using State with Maybe as a monad transformer combination? Why is this pattern relatively rare, it seems? Is this program on the right track?

Andrew

— snip

module Main where

import Control.Monad.State

type Stack = [Int]

popIt :: Stack -> (Maybe Int, Stack)
popIt [] = (Nothing, [])
popIt (x:xs) = (Just x, xs)
               
pop :: State Stack (Maybe Int)
pop = state popIt

push :: Int -> State Stack (Maybe ())
push a = state $ \xs -> (Just (), a:xs)

main = do
  let a = evalState (do
                     push 3
                     push 2
                     push 1
                     pop
                     pop
                     a <- pop
                     return a
                   ) []
  print a
         
— snip

  



More information about the Beginners mailing list