我怎样才能从堆栈中弹出两个元素然后将它们作为值的总和推回?

时间:2015-09-08 21:14:30

标签: haskell state-monad

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]
  

使用" pop>> =(\ s1 - > pop>> =(\ s2 - > push enter code here)"   我应该在这写什么?

2 个答案:

答案 0 :(得分:2)

编译器可以figure out the type to fill in a blank。如果我在代码

中添加了一个洞_
add = pop >>= \s1 -> pop >>= \s2 -> push _

编译器告诉我它应该有类型Integer

   Found hole `_' with type: Integer

你可以把Integer放在那里,这是从堆栈中弹出的值的总和?

答案 1 :(得分:0)

你是说这个?

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]