-4
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?

Cirdec
  • 24,019
  • 2
  • 50
  • 100
  • 2
    Have you tried anything? – melpomene Sep 08 '15 at 21:25
  • 1
    That definition of `pop` terrifies me; its a deeply hidden partial function. I know it wouldn't be any better `fail`ing in `Identity` for a stack underflow, but it would be less terrifying. – Cirdec Sep 08 '15 at 21:35

2 Answers2

2

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?

Cirdec
  • 24,019
  • 2
  • 50
  • 100
0

You mean this?

popAndSum :: Int -> [Int] -> [Int]
popAndSum elem list = fst xs ++ [sum']
        where
            xs = splitAt ((length list) - elem) list
            sum' = foldl (+) 0 $ snd xs

popAndSum 2 [1,2,3,4,5] = [1,2,3,9]

popAndSum 3 [1,2,3,4,5] = [1,2,12]

MaC
  • 529
  • 7
  • 14