this is my first time posting on StackOverflow. I am learning Haskell and am trying to make a function test that manipulates a stack. It takes an integer list as input and then does the following:
- If the number is even:
- If the number is 24 and there are no occurrences of 2 in the input list up to the current index, then we throw an error.
- Otherwise, we push the number to the stack.
- E.g.
list = [0,1,2,3,4,24]. There is an occurrence of 2 in the list, so we push 24 to the stack.
- If the number is odd:
- If the top of the stack == current number - 1, we pop from the stack. Otherwise, we throw an error.
- If the stack is empty after popping the stack, we display a "success" message.
At the moment I have managed to implement the stack, where I think the push, pop, peek operations have O(1) complexity, though I believe there must be a better way to implement it:
emptyStack :: [a]
emptyStack = []
push :: a -> [a] -> [a]
push item xs = item : xs
pop :: [a] -> [a]
pop [] = error "Cannot pop from empty stack."
pop xs = tail xs
peek :: [a] -> a
peek = head
And for the test function, this is what I have came up with this monstrosity which doesn't iterate through the list and the stack = emptyStack does not make sense:
test :: Integral a => [a] -> Either String [a]
test [] = Left "Empty input list"
test (x:xs) | even x = if x == 24 && notElem 2 (x:xs) then Left "Error!"
else Right (push x stack)
| odd x = if null (Right (pop xs)) then Left "Success~" else
(if peek stack == x - 1 then Right (pop stack)
else Left "Not 1 less than current number!")
where stack = emptyStack
How should my test implementation be modified to suit the requirements mentioned at the beginning? Thanks in advance!