Search code examples
haskellstate-monad

how can i pop two elements from a stack and then push in stack them back as sum of values?


import Control.Monad.State

type Stack = [Integer]

pop :: State Stack Integer
pop = state $ \(x:xs) -> (x, xs)

push :: Integer -> State Stack ()
push x = state $ \xs -> ((), (x:xs))

main :: IO()
main = print $ runState `enter code here` [1,2,3,4]

using "pop >>= (\s1 -> pop >>= (\s2 -> push enter code here)" what should i write here?


Solution

  • The compiler can figure out the type to fill in a blank. If I add a hole _ to the code

    add = pop >>= \s1 -> pop >>= \s2 -> push _
    

    The compiler tells me it should have the type Integer.

       Found hole `_' with type: Integer
    

    What Integer could you put there that would be the sum of the values popped off the stack?