Haskell 堆栈实现未按预期工作
Haskell Stack Implementation not working as expected
本人自学Haskell,自己实现了一个栈如下:
pop :: [a] -> [a]
pop [] = error "Cannot pop from an empty list!"
pop xs = init xs
push :: a -> [a] -> [a]
push = (:)
peek :: [a] -> a
peek [] = error "Cannot peek from an empty list!"
peek (x:xs) = last (x:xs)
isEmpty :: [Int] -> Bool
isEmpty [] = True
isEmpty xs = False
test :: [Int] -> Either String [Int]
test = fmap reverse . foldM step []
where step xs x | even x = Right (push x xs)
| odd x = do
var <- Right (pop xs)
if isEmpty var then Left "Successful"
else (if not (isEmpty var) then return xs else Left "Unsuccessful")
压栈是没有问题的,但是这个实现不能按预期的那样出栈,例如:
Input: [0,2,3,1]
Output: Right [0,2]
Expected: Left "Successful"
我认为问题出在 test
函数的 do
部分,但我正在努力使其工作。提前致谢!
在评论的帮助下,test
函数现在可以使用以下实现工作:
test :: [Int] -> Either String [Int]
test = fmap reverse . foldM step []
where step xs x | even x = Right (push x xs)
| odd x = if isEmpty (pop xs) then Left "Successful"
else (if not (isEmpty (pop xs)) then return (pop xs) else Left "Unsuccessful")
本人自学Haskell,自己实现了一个栈如下:
pop :: [a] -> [a]
pop [] = error "Cannot pop from an empty list!"
pop xs = init xs
push :: a -> [a] -> [a]
push = (:)
peek :: [a] -> a
peek [] = error "Cannot peek from an empty list!"
peek (x:xs) = last (x:xs)
isEmpty :: [Int] -> Bool
isEmpty [] = True
isEmpty xs = False
test :: [Int] -> Either String [Int]
test = fmap reverse . foldM step []
where step xs x | even x = Right (push x xs)
| odd x = do
var <- Right (pop xs)
if isEmpty var then Left "Successful"
else (if not (isEmpty var) then return xs else Left "Unsuccessful")
压栈是没有问题的,但是这个实现不能按预期的那样出栈,例如:
Input: [0,2,3,1]
Output: Right [0,2]
Expected: Left "Successful"
我认为问题出在 test
函数的 do
部分,但我正在努力使其工作。提前致谢!
在评论的帮助下,test
函数现在可以使用以下实现工作:
test :: [Int] -> Either String [Int]
test = fmap reverse . foldM step []
where step xs x | even x = Right (push x xs)
| odd x = if isEmpty (pop xs) then Left "Successful"
else (if not (isEmpty (pop xs)) then return (pop xs) else Left "Unsuccessful")