Question Finish this program which creates a stack and then uses a do block to alter the list of chars “ct” so that it is “cat”.

You will need to implement the push and pop functions.

import Data.Functor.Identity
import Control.Monad.State

type Stack a = State [a]

processAsStack :: 
   [a] -> Stack a () -> [a]
processAsStack lst process =
   snd (runState process lst)

pop ::  Stack a a 
pop  = state $ \(x:xs) -> (x,xs)
-- removes x from the list

push :: a -> Stack a () 
-- adds the argument to the list

printList lst = putStrLn (show lst)

main =
 printList  $
   processAsStack 
     "ct" 
     $ do 
        x <- pop
        push 'a'
        push x 

Do you understand how Haskell knows what kind of thing pop is? The do block is passed as the second argument to processAsStack so Haskell knows the do block is a Stack a monadic object. The do block therefore will have a runState function that maps a list of as to the kind of thing wrapped in a Stack a which is a list of as (because a Stack a is a State [a] which contains a list of as).

Since in its unsugared form, the do block begins with

pop >>= …

pop itself must be a function that takes a list and produces a list.