我如何从堆栈中弹出两个元素,然后将它们作为值的总和推回堆栈?
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?
编译器可以figure out the type to fill in a blank。如果我在代码
中添加一个洞_
add = pop >>= \s1 -> pop >>= \s2 -> push _
编译器告诉我它的类型应该是 Integer
.
Found hole `_' with type: Integer
你能把什么 Integer
放在那里作为从堆栈弹出的值的总和?
你是这个意思?
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]
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?
编译器可以figure out the type to fill in a blank。如果我在代码
中添加一个洞_
add = pop >>= \s1 -> pop >>= \s2 -> push _
编译器告诉我它的类型应该是 Integer
.
Found hole `_' with type: Integer
你能把什么 Integer
放在那里作为从堆栈弹出的值的总和?
你是这个意思?
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]